repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
|---|---|---|
go1.11.5
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.11.5/main.go
|
// 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.
// The go1.11.5 command runs the go command from Go 1.11.5.
//
// To install, run:
//
// $ go install golang.org/dl/go1.11.5@latest
// $ go1.11.5 download
//
// And then use the go1.11.5 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.11.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.11.5")
}
|
go1.19.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.19.9/main.go
|
// 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.
// The go1.19.9 command runs the go command from Go 1.19.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.19.9@latest
// $ go1.19.9 download
//
// And then use the go1.19.9 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.19.9.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.19.9")
}
|
go1.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.9/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.9 command runs the go command from Go 1.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.9@latest
// $ go1.9 download
//
// And then use the go1.9 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/go1.9
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.9")
}
|
go1.10.4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.10.4/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.10.4 command runs the go command from Go 1.10.4.
//
// To install, run:
//
// $ go install golang.org/dl/go1.10.4@latest
// $ go1.10.4 download
//
// And then use the go1.10.4 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.10.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.10.4")
}
|
go1.21.12
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.12/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.12 command runs the go command from Go 1.21.12.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.12@latest
// $ go1.21.12 download
//
// And then use the go1.21.12 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.12.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.12")
}
|
go1.17.5
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.5/main.go
|
// 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.
// The go1.17.5 command runs the go command from Go 1.17.5.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.5@latest
// $ go1.17.5 download
//
// And then use the go1.17.5 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.17.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.5")
}
|
go1.13rc1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.13rc1/main.go
|
// 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.
// The go1.13rc1 command runs the go command from Go 1.13rc1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.13rc1@latest
// $ go1.13rc1 download
//
// And then use the go1.13rc1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.13
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.13rc1")
}
|
go1.17.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.9/main.go
|
// 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.
// The go1.17.9 command runs the go command from Go 1.17.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.9@latest
// $ go1.17.9 download
//
// And then use the go1.17.9 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.17.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.9")
}
|
go1.22.5
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.22.5/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.22.5 command runs the go command from Go 1.22.5.
//
// To install, run:
//
// $ go install golang.org/dl/go1.22.5@latest
// $ go1.22.5 download
//
// And then use the go1.22.5 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.22.5.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.22.5")
}
|
go1.16.14
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.16.14/main.go
|
// 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.
// The go1.16.14 command runs the go command from Go 1.16.14.
//
// To install, run:
//
// $ go install golang.org/dl/go1.16.14@latest
// $ go1.16.14 download
//
// And then use the go1.16.14 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.16.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.16.14")
}
|
go1.15.1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.15.1/main.go
|
// 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.
// The go1.15.1 command runs the go command from Go 1.15.1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.15.1@latest
// $ go1.15.1 download
//
// And then use the go1.15.1 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.15.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.15.1")
}
|
go1.16beta1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.16beta1/main.go
|
// 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.
// The go1.16beta1 command runs the go command from Go 1.16beta1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.16beta1@latest
// $ go1.16beta1 download
//
// And then use the go1.16beta1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.16
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.16beta1")
}
|
go1.13beta1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.13beta1/main.go
|
// 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.
// The go1.13beta1 command runs the go command from Go 1.13beta1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.13beta1@latest
// $ go1.13beta1 download
//
// And then use the go1.13beta1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.13
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.13beta1")
}
|
go1.21.11
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.11/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.11 command runs the go command from Go 1.21.11.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.11@latest
// $ go1.21.11 download
//
// And then use the go1.21.11 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.11.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.11")
}
|
go1.17.4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.4/main.go
|
// 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.
// The go1.17.4 command runs the go command from Go 1.17.4.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.4@latest
// $ go1.17.4 download
//
// And then use the go1.17.4 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.17.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.4")
}
|
go1.8
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.8/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.8 command runs the go command from Go 1.8.
//
// To install, run:
//
// $ go install golang.org/dl/go1.8@latest
// $ go1.8 download
//
// And then use the go1.8 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/go1.8
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.8")
}
|
go1.21.10
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.10/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.10 command runs the go command from Go 1.21.10.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.10@latest
// $ go1.21.10 download
//
// And then use the go1.21.10 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.10.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.10")
}
|
go1.12.13
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.12.13/main.go
|
// 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.
// The go1.12.13 command runs the go command from Go 1.12.13.
//
// To install, run:
//
// $ go install golang.org/dl/go1.12.13@latest
// $ go1.12.13 download
//
// And then use the go1.12.13 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.12.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.12.13")
}
|
go1.15.14
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.15.14/main.go
|
// 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.
// The go1.15.14 command runs the go command from Go 1.15.14.
//
// To install, run:
//
// $ go install golang.org/dl/go1.15.14@latest
// $ go1.15.14 download
//
// And then use the go1.15.14 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.15.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.15.14")
}
|
go1.17.12
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.12/main.go
|
// 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.
// The go1.17.12 command runs the go command from Go 1.17.12.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.12@latest
// $ go1.17.12 download
//
// And then use the go1.17.12 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.17.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.12")
}
|
go1.18.8
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.18.8/main.go
|
// 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.
// The go1.18.8 command runs the go command from Go 1.18.8.
//
// To install, run:
//
// $ go install golang.org/dl/go1.18.8@latest
// $ go1.18.8 download
//
// And then use the go1.18.8 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.18.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.18.8")
}
|
go1.20.14
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.20.14/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.20.14 command runs the go command from Go 1.20.14.
//
// To install, run:
//
// $ go install golang.org/dl/go1.20.14@latest
// $ go1.20.14 download
//
// And then use the go1.20.14 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.20.14.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.20.14")
}
|
go1.10.1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.10.1/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.10.1 command runs the go command from Go 1.10.1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.10.1@latest
// $ go1.10.1 download
//
// And then use the go1.10.1 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.10.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.10.1")
}
|
go1.12.10
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.12.10/main.go
|
// 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.
// The go1.12.10 command runs the go command from Go 1.12.10.
//
// To install, run:
//
// $ go install golang.org/dl/go1.12.10@latest
// $ go1.12.10 download
//
// And then use the go1.12.10 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.12.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.12.10")
}
|
go1.21.7
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.7/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.7 command runs the go command from Go 1.21.7.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.7@latest
// $ go1.21.7 download
//
// And then use the go1.21.7 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.7.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.7")
}
|
go1.20.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.20.9/main.go
|
// 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.
// The go1.20.9 command runs the go command from Go 1.20.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.20.9@latest
// $ go1.20.9 download
//
// And then use the go1.20.9 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.20.9.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.20.9")
}
|
go1.9.4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.9.4/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.9.4 command runs the go command from Go 1.9.4.
//
// To install, run:
//
// $ go install golang.org/dl/go1.9.4@latest
// $ go1.9.4 download
//
// And then use the go1.9.4 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.9.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.9.4")
}
|
go1.20.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.20.6/main.go
|
// 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.
// The go1.20.6 command runs the go command from Go 1.20.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.20.6@latest
// $ go1.20.6 download
//
// And then use the go1.20.6 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.20.6.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.20.6")
}
|
go1.21.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.9/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.9 command runs the go command from Go 1.21.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.9@latest
// $ go1.21.9 download
//
// And then use the go1.21.9 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.9.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.9")
}
|
go1.11.13
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.11.13/main.go
|
// 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.
// The go1.11.13 command runs the go command from Go 1.11.13.
//
// To install, run:
//
// $ go install golang.org/dl/go1.11.13@latest
// $ go1.11.13 download
//
// And then use the go1.11.13 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.11.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.11.13")
}
|
go1.17.3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.17.3/main.go
|
// 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.
// The go1.17.3 command runs the go command from Go 1.17.3.
//
// To install, run:
//
// $ go install golang.org/dl/go1.17.3@latest
// $ go1.17.3 download
//
// And then use the go1.17.3 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.17.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.17.3")
}
|
go1.12.15
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.12.15/main.go
|
// 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.
// The go1.12.15 command runs the go command from Go 1.12.15.
//
// To install, run:
//
// $ go install golang.org/dl/go1.12.15@latest
// $ go1.12.15 download
//
// And then use the go1.12.15 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.12.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.12.15")
}
|
go1.13.10
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.13.10/main.go
|
// 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.
// The go1.13.10 command runs the go command from Go 1.13.10.
//
// To install, run:
//
// $ go install golang.org/dl/go1.13.10@latest
// $ go1.13.10 download
//
// And then use the go1.13.10 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.13.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.13.10")
}
|
go1.21.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.6/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.21.6 command runs the go command from Go 1.21.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.6@latest
// $ go1.21.6 download
//
// And then use the go1.21.6 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.6.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.6")
}
|
go1.11rc2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.11rc2/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.11rc2 command runs the go command from Go 1.11rc2.
//
// To install, run:
//
// $ go install golang.org/dl/go1.11rc2@latest
// $ go1.11rc2 download
//
// And then use the go1.11rc2 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.11
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.11rc2")
}
|
go1.21.3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.3/main.go
|
// 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.
// The go1.21.3 command runs the go command from Go 1.21.3.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.3@latest
// $ go1.21.3 download
//
// And then use the go1.21.3 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.3.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.3")
}
|
go1.16.9
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.16.9/main.go
|
// 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.
// The go1.16.9 command runs the go command from Go 1.16.9.
//
// To install, run:
//
// $ go install golang.org/dl/go1.16.9@latest
// $ go1.16.9 download
//
// And then use the go1.16.9 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.16.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.16.9")
}
|
go1.12beta2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.12beta2/main.go
|
// 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.
// The go1.12beta2 command runs the go command from Go 1.12beta2.
//
// To install, run:
//
// $ go install golang.org/dl/go1.12beta2@latest
// $ go1.12beta2 download
//
// And then use the go1.12beta2 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.12
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.12beta2")
}
|
go1.22rc1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.22rc1/main.go
|
// 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.
// The go1.22rc1 command runs the go command from Go 1.22rc1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.22rc1@latest
// $ go1.22rc1 download
//
// And then use the go1.22rc1 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.22.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.22rc1")
}
|
go1.16.1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.16.1/main.go
|
// 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.
// The go1.16.1 command runs the go command from Go 1.16.1.
//
// To install, run:
//
// $ go install golang.org/dl/go1.16.1@latest
// $ go1.16.1 download
//
// And then use the go1.16.1 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.16.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.16.1")
}
|
go1.9.3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.9.3/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.9.3 command runs the go command from Go 1.9.3.
//
// To install, run:
//
// $ go install golang.org/dl/go1.9.3@latest
// $ go1.9.3 download
//
// And then use the go1.9.3 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.9.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.9.3")
}
|
go1.6.4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.6.4/main.go
|
// 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.
// The go1.6.4 command runs the go command from Go 1.6.4.
//
// To install, run:
//
// $ go install golang.org/dl/go1.6.4@latest
// $ go1.6.4 download
//
// And then use the go1.6.4 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.6.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.6.4")
}
|
go1.20.2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.20.2/main.go
|
// 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.
// The go1.20.2 command runs the go command from Go 1.20.2.
//
// To install, run:
//
// $ go install golang.org/dl/go1.20.2@latest
// $ go1.20.2 download
//
// And then use the go1.20.2 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.20.minor.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.20.2")
}
|
go1.15.6
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.15.6/main.go
|
// 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.
// The go1.15.6 command runs the go command from Go 1.15.6.
//
// To install, run:
//
// $ go install golang.org/dl/go1.15.6@latest
// $ go1.15.6 download
//
// And then use the go1.15.6 command as if it were your normal go
// command.
//
// See the release notes at https://golang.org/doc/devel/release.html#go1.15.minor
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.15.6")
}
|
go1.8rc3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.8rc3/main.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The go1.8rc3 command runs the go command from Go 1.8rc3.
//
// To install, run:
//
// $ go install golang.org/dl/go1.8rc3@latest
// $ go1.8rc3 download
//
// And then use the go1.8rc3 command as if it were your normal go
// command.
//
// See the release notes at https://tip.golang.org/doc/go1.8
//
// File bugs at https://golang.org/issues/new
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.8rc3")
}
|
go1.21.4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/dl/go1.21.4/main.go
|
// 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.
// The go1.21.4 command runs the go command from Go 1.21.4.
//
// To install, run:
//
// $ go install golang.org/dl/go1.21.4@latest
// $ go1.21.4 download
//
// And then use the go1.21.4 command as if it were your normal go
// command.
//
// See the release notes at https://go.dev/doc/devel/release#go1.21.4.
//
// File bugs at https://go.dev/issue/new.
package main
import "golang.org/dl/internal/version"
func main() {
version.Run("go1.21.4")
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_unix_other.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build aix || linux || solaris || zos
package term
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TCGETS
const ioctlWriteTermios = unix.TCSETS
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/CONTRIBUTING.md
|
# Contributing to Go
Go is an open source project.
It is the work of hundreds of contributors. We appreciate your help!
## Filing issues
When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
## Contributing code
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.
Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/terminal_test.go
|
// 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 term
import (
"bytes"
"io"
"os"
"runtime"
"testing"
)
type MockTerminal struct {
toSend []byte
bytesPerRead int
received []byte
}
func (c *MockTerminal) Read(data []byte) (n int, err error) {
n = len(data)
if n == 0 {
return
}
if n > len(c.toSend) {
n = len(c.toSend)
}
if n == 0 {
return 0, io.EOF
}
if c.bytesPerRead > 0 && n > c.bytesPerRead {
n = c.bytesPerRead
}
copy(data, c.toSend[:n])
c.toSend = c.toSend[n:]
return
}
func (c *MockTerminal) Write(data []byte) (n int, err error) {
c.received = append(c.received, data...)
return len(data), nil
}
func TestClose(t *testing.T) {
c := &MockTerminal{}
ss := NewTerminal(c, "> ")
line, err := ss.ReadLine()
if line != "" {
t.Errorf("Expected empty line but got: %s", line)
}
if err != io.EOF {
t.Errorf("Error should have been EOF but got: %s", err)
}
}
var keyPressTests = []struct {
in string
line string
err error
throwAwayLines int
}{
{
err: io.EOF,
},
{
in: "\r",
line: "",
},
{
in: "foo\r",
line: "foo",
},
{
in: "a\x1b[Cb\r", // right
line: "ab",
},
{
in: "a\x1b[Db\r", // left
line: "ba",
},
{
in: "a\006b\r", // ^F
line: "ab",
},
{
in: "a\002b\r", // ^B
line: "ba",
},
{
in: "a\177b\r", // backspace
line: "b",
},
{
in: "\x1b[A\r", // up
},
{
in: "\x1b[B\r", // down
},
{
in: "\016\r", // ^P
},
{
in: "\014\r", // ^N
},
{
in: "line\x1b[A\x1b[B\r", // up then down
line: "line",
},
{
in: "line1\rline2\x1b[A\r", // recall previous line.
line: "line1",
throwAwayLines: 1,
},
{
// recall two previous lines and append.
in: "line1\rline2\rline3\x1b[A\x1b[Axxx\r",
line: "line1xxx",
throwAwayLines: 2,
},
{
// Ctrl-A to move to beginning of line followed by ^K to kill
// line.
in: "a b \001\013\r",
line: "",
},
{
// Ctrl-A to move to beginning of line, Ctrl-E to move to end,
// finally ^K to kill nothing.
in: "a b \001\005\013\r",
line: "a b ",
},
{
in: "\027\r",
line: "",
},
{
in: "a\027\r",
line: "",
},
{
in: "a \027\r",
line: "",
},
{
in: "a b\027\r",
line: "a ",
},
{
in: "a b \027\r",
line: "a ",
},
{
in: "one two thr\x1b[D\027\r",
line: "one two r",
},
{
in: "\013\r",
line: "",
},
{
in: "a\013\r",
line: "a",
},
{
in: "ab\x1b[D\013\r",
line: "a",
},
{
in: "Ξεσκεπάζω\r",
line: "Ξεσκεπάζω",
},
{
in: "£\r\x1b[A\177\r", // non-ASCII char, enter, up, backspace.
line: "",
throwAwayLines: 1,
},
{
in: "£\r££\x1b[A\x1b[B\177\r", // non-ASCII char, enter, 2x non-ASCII, up, down, backspace, enter.
line: "£",
throwAwayLines: 1,
},
{
// Ctrl-D at the end of the line should be ignored.
in: "a\004\r",
line: "a",
},
{
// a, b, left, Ctrl-D should erase the b.
in: "ab\x1b[D\004\r",
line: "a",
},
{
// a, b, c, d, left, left, ^U should erase to the beginning of
// the line.
in: "abcd\x1b[D\x1b[D\025\r",
line: "cd",
},
{
// Bracketed paste mode: control sequences should be returned
// verbatim in paste mode.
in: "abc\x1b[200~de\177f\x1b[201~\177\r",
line: "abcde\177",
},
{
// Enter in bracketed paste mode should still work.
in: "abc\x1b[200~d\refg\x1b[201~h\r",
line: "efgh",
throwAwayLines: 1,
},
{
// Lines consisting entirely of pasted data should be indicated as such.
in: "\x1b[200~a\r",
line: "a",
err: ErrPasteIndicator,
},
{
// Ctrl-C terminates readline
in: "\003",
err: io.EOF,
},
{
// Ctrl-C at the end of line also terminates readline
in: "a\003\r",
err: io.EOF,
},
}
func TestKeyPresses(t *testing.T) {
for i, test := range keyPressTests {
for j := 1; j < len(test.in); j++ {
c := &MockTerminal{
toSend: []byte(test.in),
bytesPerRead: j,
}
ss := NewTerminal(c, "> ")
for k := 0; k < test.throwAwayLines; k++ {
_, err := ss.ReadLine()
if err != nil {
t.Errorf("Throwaway line %d from test %d resulted in error: %s", k, i, err)
}
}
line, err := ss.ReadLine()
if line != test.line {
t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line)
break
}
if err != test.err {
t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
break
}
}
}
}
var renderTests = []struct {
in string
received string
err error
}{
{
// Cursor move after keyHome (left 4) then enter (right 4, newline)
in: "abcd\x1b[H\r",
received: "> abcd\x1b[4D\x1b[4C\r\n",
},
{
// Write, home, prepend, enter. Prepends rewrites the line.
in: "cdef\x1b[Hab\r",
received: "> cdef" + // Initial input
"\x1b[4Da" + // Move cursor back, insert first char
"cdef" + // Copy over original string
"\x1b[4Dbcdef" + // Repeat for second char with copy
"\x1b[4D" + // Put cursor back in position to insert again
"\x1b[4C\r\n", // Put cursor at the end of the line and newline.
},
}
func TestRender(t *testing.T) {
for i, test := range renderTests {
for j := 1; j < len(test.in); j++ {
c := &MockTerminal{
toSend: []byte(test.in),
bytesPerRead: j,
}
ss := NewTerminal(c, "> ")
_, err := ss.ReadLine()
if err != test.err {
t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
break
}
if test.received != string(c.received) {
t.Errorf("Results rendered from test %d (%d bytes per read) was '%s', expected '%s'", i, j, c.received, test.received)
break
}
}
}
}
func TestPasswordNotSaved(t *testing.T) {
c := &MockTerminal{
toSend: []byte("password\r\x1b[A\r"),
bytesPerRead: 1,
}
ss := NewTerminal(c, "> ")
pw, _ := ss.ReadPassword("> ")
if pw != "password" {
t.Fatalf("failed to read password, got %s", pw)
}
line, _ := ss.ReadLine()
if len(line) > 0 {
t.Fatalf("password was saved in history")
}
}
var setSizeTests = []struct {
width, height int
}{
{40, 13},
{80, 24},
{132, 43},
}
func TestTerminalSetSize(t *testing.T) {
for _, setSize := range setSizeTests {
c := &MockTerminal{
toSend: []byte("password\r\x1b[A\r"),
bytesPerRead: 1,
}
ss := NewTerminal(c, "> ")
ss.SetSize(setSize.width, setSize.height)
pw, _ := ss.ReadPassword("Password: ")
if pw != "password" {
t.Fatalf("failed to read password, got %s", pw)
}
if string(c.received) != "Password: \r\n" {
t.Errorf("failed to set the temporary prompt expected %q, got %q", "Password: ", c.received)
}
}
}
func TestReadPasswordLineEnd(t *testing.T) {
type testType struct {
input string
want string
}
var tests = []testType{
{"\r\n", ""},
{"test\r\n", "test"},
{"test\r", "test"},
{"test\n", "test"},
{"testtesttesttes\n", "testtesttesttes"},
{"testtesttesttes\r\n", "testtesttesttes"},
{"testtesttesttesttest\n", "testtesttesttesttest"},
{"testtesttesttesttest\r\n", "testtesttesttesttest"},
{"\btest", "test"},
{"t\best", "est"},
{"te\bst", "tst"},
{"test\b", "tes"},
{"test\b\r\n", "tes"},
{"test\b\n", "tes"},
{"test\b\r", "tes"},
}
eol := "\n"
if runtime.GOOS == "windows" {
eol = "\r"
}
tests = append(tests, testType{eol, ""})
for _, test := range tests {
buf := new(bytes.Buffer)
if _, err := buf.WriteString(test.input); err != nil {
t.Fatal(err)
}
have, err := readPasswordLine(buf)
if err != nil {
t.Errorf("readPasswordLine(%q) failed: %v", test.input, err)
continue
}
if string(have) != test.want {
t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want)
continue
}
if _, err = buf.WriteString(test.input); err != nil {
t.Fatal(err)
}
have, err = readPasswordLine(buf)
if err != nil {
t.Errorf("readPasswordLine(%q) failed: %v", test.input, err)
continue
}
if string(have) != test.want {
t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want)
continue
}
}
}
func TestMakeRawState(t *testing.T) {
fd := int(os.Stdout.Fd())
if !IsTerminal(fd) {
t.Skip("stdout is not a terminal; skipping test")
}
st, err := GetState(fd)
if err != nil {
t.Fatalf("failed to get terminal state from GetState: %s", err)
}
if runtime.GOOS == "ios" {
t.Skip("MakeRaw not allowed on iOS; skipping test")
}
defer Restore(fd, st)
raw, err := MakeRaw(fd)
if err != nil {
t.Fatalf("failed to get terminal state from MakeRaw: %s", err)
}
if *st != *raw {
t.Errorf("states do not match; was %v, expected %v", raw, st)
}
}
func TestOutputNewlines(t *testing.T) {
// \n should be changed to \r\n in terminal output.
buf := new(bytes.Buffer)
term := NewTerminal(buf, ">")
term.Write([]byte("1\n2\n"))
output := buf.String()
const expected = "1\r\n2\r\n"
if output != expected {
t.Errorf("incorrect output: was %q, expected %q", output, expected)
}
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/PATENTS
|
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_unsupported.go
|
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !zos && !windows && !solaris && !plan9
package term
import (
"fmt"
"runtime"
)
type state struct{}
func isTerminal(fd int) bool {
return false
}
func makeRaw(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: MakeRaw not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func getState(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: GetState not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func restore(fd int, state *State) error {
return fmt.Errorf("terminal: Restore not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func getSize(fd int) (width, height int, err error) {
return 0, 0, fmt.Errorf("terminal: GetSize not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func readPassword(fd int) ([]byte, error) {
return nil, fmt.Errorf("terminal: ReadPassword not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_unix.go
|
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
package term
import (
"golang.org/x/sys/unix"
)
type state struct {
termios unix.Termios
}
func isTerminal(fd int) bool {
_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
return err == nil
}
func makeRaw(fd int) (*State, error) {
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
if err != nil {
return nil, err
}
oldState := State{state{termios: *termios}}
// This attempts to replicate the behaviour documented for cfmakeraw in
// the termios(3) manpage.
termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
termios.Oflag &^= unix.OPOST
termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
termios.Cflag &^= unix.CSIZE | unix.PARENB
termios.Cflag |= unix.CS8
termios.Cc[unix.VMIN] = 1
termios.Cc[unix.VTIME] = 0
if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, termios); err != nil {
return nil, err
}
return &oldState, nil
}
func getState(fd int) (*State, error) {
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
if err != nil {
return nil, err
}
return &State{state{termios: *termios}}, nil
}
func restore(fd int, state *State) error {
return unix.IoctlSetTermios(fd, ioctlWriteTermios, &state.termios)
}
func getSize(fd int) (width, height int, err error) {
ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
if err != nil {
return 0, 0, err
}
return int(ws.Col), int(ws.Row), nil
}
// passwordReader is an io.Reader that reads from a specific file descriptor.
type passwordReader int
func (r passwordReader) Read(buf []byte) (int, error) {
return unix.Read(int(r), buf)
}
func readPassword(fd int) ([]byte, error) {
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
if err != nil {
return nil, err
}
newState := *termios
newState.Lflag &^= unix.ECHO
newState.Lflag |= unix.ICANON | unix.ISIG
newState.Iflag |= unix.ICRNL
if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, &newState); err != nil {
return nil, err
}
defer unix.IoctlSetTermios(fd, ioctlWriteTermios, termios)
return readPasswordLine(passwordReader(fd))
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/go.mod
|
module golang.org/x/term
go 1.18
require golang.org/x/sys v0.22.0
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/README.md
|
# Go terminal/console support
[](https://pkg.go.dev/golang.org/x/term)
This repository provides Go terminal and console support packages.
## Download/Install
The easiest way to install is to run `go get -u golang.org/x/term`. You can
also manually git clone the repository to `$GOPATH/src/golang.org/x/term`.
## 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 term repository is located at
https://github.com/golang/go/issues. Prefix your issue with "x/term:" in the
subject line, so it is easy to find.
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_windows.go
|
// 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 term
import (
"os"
"golang.org/x/sys/windows"
)
type state struct {
mode uint32
}
func isTerminal(fd int) bool {
var st uint32
err := windows.GetConsoleMode(windows.Handle(fd), &st)
return err == nil
}
func makeRaw(fd int) (*State, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
return nil, err
}
return &State{state{st}}, nil
}
func getState(fd int) (*State, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
return &State{state{st}}, nil
}
func restore(fd int, state *State) error {
return windows.SetConsoleMode(windows.Handle(fd), state.mode)
}
func getSize(fd int) (width, height int, err error) {
var info windows.ConsoleScreenBufferInfo
if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil {
return 0, 0, err
}
return int(info.Window.Right - info.Window.Left + 1), int(info.Window.Bottom - info.Window.Top + 1), nil
}
func readPassword(fd int) ([]byte, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
old := st
st &^= (windows.ENABLE_ECHO_INPUT | windows.ENABLE_LINE_INPUT)
st |= (windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_PROCESSED_INPUT)
if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil {
return nil, err
}
defer windows.SetConsoleMode(windows.Handle(fd), old)
var h windows.Handle
p, _ := windows.GetCurrentProcess()
if err := windows.DuplicateHandle(p, windows.Handle(fd), p, &h, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil {
return nil, err
}
f := os.NewFile(uintptr(h), "stdin")
defer f.Close()
return readPasswordLine(f)
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/go.sum
|
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term.go
|
// 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 term provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
// if err != nil {
// panic(err)
// }
// defer term.Restore(int(os.Stdin.Fd()), oldState)
//
// Note that on non-Unix systems os.Stdin.Fd() may not be 0.
package term
// State contains the state of a terminal.
type State struct {
state
}
// IsTerminal returns whether the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
return isTerminal(fd)
}
// MakeRaw puts the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
return makeRaw(fd)
}
// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
return getState(fd)
}
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, oldState *State) error {
return restore(fd, oldState)
}
// GetSize returns the visible dimensions of the given terminal.
//
// These dimensions don't include any scrollback buffer height.
func GetSize(fd int) (width, height int, err error) {
return getSize(fd)
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
return readPassword(fd)
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_test.go
|
// 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 term_test
import (
"os"
"runtime"
"testing"
"golang.org/x/term"
)
func TestIsTerminalTempFile(t *testing.T) {
file, err := os.CreateTemp("", "TestIsTerminalTempFile")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
defer file.Close()
if term.IsTerminal(int(file.Fd())) {
t.Fatalf("IsTerminal unexpectedly returned true for temporary file %s", file.Name())
}
}
func TestIsTerminalTerm(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skipf("unknown terminal path for GOOS %v", runtime.GOOS)
}
file, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if !term.IsTerminal(int(file.Fd())) {
t.Fatalf("IsTerminal unexpectedly returned false for terminal file %s", file.Name())
}
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/terminal.go
|
// 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 term
import (
"bytes"
"io"
"runtime"
"strconv"
"sync"
"unicode/utf8"
)
// EscapeCodes contains escape sequences that can be written to the terminal in
// order to achieve different styles of text.
type EscapeCodes struct {
// Foreground colors
Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
// Reset all attributes
Reset []byte
}
var vt100EscapeCodes = EscapeCodes{
Black: []byte{keyEscape, '[', '3', '0', 'm'},
Red: []byte{keyEscape, '[', '3', '1', 'm'},
Green: []byte{keyEscape, '[', '3', '2', 'm'},
Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
Blue: []byte{keyEscape, '[', '3', '4', 'm'},
Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
White: []byte{keyEscape, '[', '3', '7', 'm'},
Reset: []byte{keyEscape, '[', '0', 'm'},
}
// Terminal contains the state for running a VT100 terminal that is capable of
// reading lines of input.
type Terminal struct {
// AutoCompleteCallback, if non-null, is called for each keypress with
// the full input line and the current position of the cursor (in
// bytes, as an index into |line|). If it returns ok=false, the key
// press is processed normally. Otherwise it returns a replacement line
// and the new cursor position.
AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)
// Escape contains a pointer to the escape codes for this terminal.
// It's always a valid pointer, although the escape codes themselves
// may be empty if the terminal doesn't support them.
Escape *EscapeCodes
// lock protects the terminal and the state in this object from
// concurrent processing of a key press and a Write() call.
lock sync.Mutex
c io.ReadWriter
prompt []rune
// line is the current line being entered.
line []rune
// pos is the logical position of the cursor in line
pos int
// echo is true if local echo is enabled
echo bool
// pasteActive is true iff there is a bracketed paste operation in
// progress.
pasteActive bool
// cursorX contains the current X value of the cursor where the left
// edge is 0. cursorY contains the row number where the first row of
// the current line is 0.
cursorX, cursorY int
// maxLine is the greatest value of cursorY so far.
maxLine int
termWidth, termHeight int
// outBuf contains the terminal data to be sent.
outBuf []byte
// remainder contains the remainder of any partial key sequences after
// a read. It aliases into inBuf.
remainder []byte
inBuf [256]byte
// history contains previously entered commands so that they can be
// accessed with the up and down keys.
history stRingBuffer
// historyIndex stores the currently accessed history entry, where zero
// means the immediately previous entry.
historyIndex int
// When navigating up and down the history it's possible to return to
// the incomplete, initial line. That value is stored in
// historyPending.
historyPending string
}
// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
// a local terminal, that terminal must first have been put into raw mode.
// prompt is a string that is written at the start of each input line (i.e.
// "> ").
func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
return &Terminal{
Escape: &vt100EscapeCodes,
c: c,
prompt: []rune(prompt),
termWidth: 80,
termHeight: 24,
echo: true,
historyIndex: -1,
}
}
const (
keyCtrlC = 3
keyCtrlD = 4
keyCtrlU = 21
keyEnter = '\r'
keyEscape = 27
keyBackspace = 127
keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
keyUp
keyDown
keyLeft
keyRight
keyAltLeft
keyAltRight
keyHome
keyEnd
keyDeleteWord
keyDeleteLine
keyClearScreen
keyPasteStart
keyPasteEnd
)
var (
crlf = []byte{'\r', '\n'}
pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
)
// bytesToKey tries to parse a key sequence from b. If successful, it returns
// the key and the remainder of the input. Otherwise it returns utf8.RuneError.
func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
if len(b) == 0 {
return utf8.RuneError, nil
}
if !pasteActive {
switch b[0] {
case 1: // ^A
return keyHome, b[1:]
case 2: // ^B
return keyLeft, b[1:]
case 5: // ^E
return keyEnd, b[1:]
case 6: // ^F
return keyRight, b[1:]
case 8: // ^H
return keyBackspace, b[1:]
case 11: // ^K
return keyDeleteLine, b[1:]
case 12: // ^L
return keyClearScreen, b[1:]
case 23: // ^W
return keyDeleteWord, b[1:]
case 14: // ^N
return keyDown, b[1:]
case 16: // ^P
return keyUp, b[1:]
}
}
if b[0] != keyEscape {
if !utf8.FullRune(b) {
return utf8.RuneError, b
}
r, l := utf8.DecodeRune(b)
return r, b[l:]
}
if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
switch b[2] {
case 'A':
return keyUp, b[3:]
case 'B':
return keyDown, b[3:]
case 'C':
return keyRight, b[3:]
case 'D':
return keyLeft, b[3:]
case 'H':
return keyHome, b[3:]
case 'F':
return keyEnd, b[3:]
}
}
if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
switch b[5] {
case 'C':
return keyAltRight, b[6:]
case 'D':
return keyAltLeft, b[6:]
}
}
if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
return keyPasteStart, b[6:]
}
if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
return keyPasteEnd, b[6:]
}
// If we get here then we have a key that we don't recognise, or a
// partial sequence. It's not clear how one should find the end of a
// sequence without knowing them all, but it seems that [a-zA-Z~] only
// appears at the end of a sequence.
for i, c := range b[0:] {
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
return keyUnknown, b[i+1:]
}
}
return utf8.RuneError, b
}
// queue appends data to the end of t.outBuf
func (t *Terminal) queue(data []rune) {
t.outBuf = append(t.outBuf, []byte(string(data))...)
}
var space = []rune{' '}
func isPrintable(key rune) bool {
isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
return key >= 32 && !isInSurrogateArea
}
// moveCursorToPos appends data to t.outBuf which will move the cursor to the
// given, logical position in the text.
func (t *Terminal) moveCursorToPos(pos int) {
if !t.echo {
return
}
x := visualLength(t.prompt) + pos
y := x / t.termWidth
x = x % t.termWidth
up := 0
if y < t.cursorY {
up = t.cursorY - y
}
down := 0
if y > t.cursorY {
down = y - t.cursorY
}
left := 0
if x < t.cursorX {
left = t.cursorX - x
}
right := 0
if x > t.cursorX {
right = x - t.cursorX
}
t.cursorX = x
t.cursorY = y
t.move(up, down, left, right)
}
func (t *Terminal) move(up, down, left, right int) {
m := []rune{}
// 1 unit up can be expressed as ^[[A or ^[A
// 5 units up can be expressed as ^[[5A
if up == 1 {
m = append(m, keyEscape, '[', 'A')
} else if up > 1 {
m = append(m, keyEscape, '[')
m = append(m, []rune(strconv.Itoa(up))...)
m = append(m, 'A')
}
if down == 1 {
m = append(m, keyEscape, '[', 'B')
} else if down > 1 {
m = append(m, keyEscape, '[')
m = append(m, []rune(strconv.Itoa(down))...)
m = append(m, 'B')
}
if right == 1 {
m = append(m, keyEscape, '[', 'C')
} else if right > 1 {
m = append(m, keyEscape, '[')
m = append(m, []rune(strconv.Itoa(right))...)
m = append(m, 'C')
}
if left == 1 {
m = append(m, keyEscape, '[', 'D')
} else if left > 1 {
m = append(m, keyEscape, '[')
m = append(m, []rune(strconv.Itoa(left))...)
m = append(m, 'D')
}
t.queue(m)
}
func (t *Terminal) clearLineToRight() {
op := []rune{keyEscape, '[', 'K'}
t.queue(op)
}
const maxLineLength = 4096
func (t *Terminal) setLine(newLine []rune, newPos int) {
if t.echo {
t.moveCursorToPos(0)
t.writeLine(newLine)
for i := len(newLine); i < len(t.line); i++ {
t.writeLine(space)
}
t.moveCursorToPos(newPos)
}
t.line = newLine
t.pos = newPos
}
func (t *Terminal) advanceCursor(places int) {
t.cursorX += places
t.cursorY += t.cursorX / t.termWidth
if t.cursorY > t.maxLine {
t.maxLine = t.cursorY
}
t.cursorX = t.cursorX % t.termWidth
if places > 0 && t.cursorX == 0 {
// Normally terminals will advance the current position
// when writing a character. But that doesn't happen
// for the last character in a line. However, when
// writing a character (except a new line) that causes
// a line wrap, the position will be advanced two
// places.
//
// So, if we are stopping at the end of a line, we
// need to write a newline so that our cursor can be
// advanced to the next line.
t.outBuf = append(t.outBuf, '\r', '\n')
}
}
func (t *Terminal) eraseNPreviousChars(n int) {
if n == 0 {
return
}
if t.pos < n {
n = t.pos
}
t.pos -= n
t.moveCursorToPos(t.pos)
copy(t.line[t.pos:], t.line[n+t.pos:])
t.line = t.line[:len(t.line)-n]
if t.echo {
t.writeLine(t.line[t.pos:])
for i := 0; i < n; i++ {
t.queue(space)
}
t.advanceCursor(n)
t.moveCursorToPos(t.pos)
}
}
// countToLeftWord returns then number of characters from the cursor to the
// start of the previous word.
func (t *Terminal) countToLeftWord() int {
if t.pos == 0 {
return 0
}
pos := t.pos - 1
for pos > 0 {
if t.line[pos] != ' ' {
break
}
pos--
}
for pos > 0 {
if t.line[pos] == ' ' {
pos++
break
}
pos--
}
return t.pos - pos
}
// countToRightWord returns then number of characters from the cursor to the
// start of the next word.
func (t *Terminal) countToRightWord() int {
pos := t.pos
for pos < len(t.line) {
if t.line[pos] == ' ' {
break
}
pos++
}
for pos < len(t.line) {
if t.line[pos] != ' ' {
break
}
pos++
}
return pos - t.pos
}
// visualLength returns the number of visible glyphs in s.
func visualLength(runes []rune) int {
inEscapeSeq := false
length := 0
for _, r := range runes {
switch {
case inEscapeSeq:
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
inEscapeSeq = false
}
case r == '\x1b':
inEscapeSeq = true
default:
length++
}
}
return length
}
// handleKey processes the given key and, optionally, returns a line of text
// that the user has entered.
func (t *Terminal) handleKey(key rune) (line string, ok bool) {
if t.pasteActive && key != keyEnter {
t.addKeyToLine(key)
return
}
switch key {
case keyBackspace:
if t.pos == 0 {
return
}
t.eraseNPreviousChars(1)
case keyAltLeft:
// move left by a word.
t.pos -= t.countToLeftWord()
t.moveCursorToPos(t.pos)
case keyAltRight:
// move right by a word.
t.pos += t.countToRightWord()
t.moveCursorToPos(t.pos)
case keyLeft:
if t.pos == 0 {
return
}
t.pos--
t.moveCursorToPos(t.pos)
case keyRight:
if t.pos == len(t.line) {
return
}
t.pos++
t.moveCursorToPos(t.pos)
case keyHome:
if t.pos == 0 {
return
}
t.pos = 0
t.moveCursorToPos(t.pos)
case keyEnd:
if t.pos == len(t.line) {
return
}
t.pos = len(t.line)
t.moveCursorToPos(t.pos)
case keyUp:
entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
if !ok {
return "", false
}
if t.historyIndex == -1 {
t.historyPending = string(t.line)
}
t.historyIndex++
runes := []rune(entry)
t.setLine(runes, len(runes))
case keyDown:
switch t.historyIndex {
case -1:
return
case 0:
runes := []rune(t.historyPending)
t.setLine(runes, len(runes))
t.historyIndex--
default:
entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
if ok {
t.historyIndex--
runes := []rune(entry)
t.setLine(runes, len(runes))
}
}
case keyEnter:
t.moveCursorToPos(len(t.line))
t.queue([]rune("\r\n"))
line = string(t.line)
ok = true
t.line = t.line[:0]
t.pos = 0
t.cursorX = 0
t.cursorY = 0
t.maxLine = 0
case keyDeleteWord:
// Delete zero or more spaces and then one or more characters.
t.eraseNPreviousChars(t.countToLeftWord())
case keyDeleteLine:
// Delete everything from the current cursor position to the
// end of line.
for i := t.pos; i < len(t.line); i++ {
t.queue(space)
t.advanceCursor(1)
}
t.line = t.line[:t.pos]
t.moveCursorToPos(t.pos)
case keyCtrlD:
// Erase the character under the current position.
// The EOF case when the line is empty is handled in
// readLine().
if t.pos < len(t.line) {
t.pos++
t.eraseNPreviousChars(1)
}
case keyCtrlU:
t.eraseNPreviousChars(t.pos)
case keyClearScreen:
// Erases the screen and moves the cursor to the home position.
t.queue([]rune("\x1b[2J\x1b[H"))
t.queue(t.prompt)
t.cursorX, t.cursorY = 0, 0
t.advanceCursor(visualLength(t.prompt))
t.setLine(t.line, t.pos)
default:
if t.AutoCompleteCallback != nil {
prefix := string(t.line[:t.pos])
suffix := string(t.line[t.pos:])
t.lock.Unlock()
newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
t.lock.Lock()
if completeOk {
t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
return
}
}
if !isPrintable(key) {
return
}
if len(t.line) == maxLineLength {
return
}
t.addKeyToLine(key)
}
return
}
// addKeyToLine inserts the given key at the current position in the current
// line.
func (t *Terminal) addKeyToLine(key rune) {
if len(t.line) == cap(t.line) {
newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
copy(newLine, t.line)
t.line = newLine
}
t.line = t.line[:len(t.line)+1]
copy(t.line[t.pos+1:], t.line[t.pos:])
t.line[t.pos] = key
if t.echo {
t.writeLine(t.line[t.pos:])
}
t.pos++
t.moveCursorToPos(t.pos)
}
func (t *Terminal) writeLine(line []rune) {
for len(line) != 0 {
remainingOnLine := t.termWidth - t.cursorX
todo := len(line)
if todo > remainingOnLine {
todo = remainingOnLine
}
t.queue(line[:todo])
t.advanceCursor(visualLength(line[:todo]))
line = line[todo:]
}
}
// writeWithCRLF writes buf to w but replaces all occurrences of \n with \r\n.
func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) {
for len(buf) > 0 {
i := bytes.IndexByte(buf, '\n')
todo := len(buf)
if i >= 0 {
todo = i
}
var nn int
nn, err = w.Write(buf[:todo])
n += nn
if err != nil {
return n, err
}
buf = buf[todo:]
if i >= 0 {
if _, err = w.Write(crlf); err != nil {
return n, err
}
n++
buf = buf[1:]
}
}
return n, nil
}
func (t *Terminal) Write(buf []byte) (n int, err error) {
t.lock.Lock()
defer t.lock.Unlock()
if t.cursorX == 0 && t.cursorY == 0 {
// This is the easy case: there's nothing on the screen that we
// have to move out of the way.
return writeWithCRLF(t.c, buf)
}
// We have a prompt and possibly user input on the screen. We
// have to clear it first.
t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
t.cursorX = 0
t.clearLineToRight()
for t.cursorY > 0 {
t.move(1 /* up */, 0, 0, 0)
t.cursorY--
t.clearLineToRight()
}
if _, err = t.c.Write(t.outBuf); err != nil {
return
}
t.outBuf = t.outBuf[:0]
if n, err = writeWithCRLF(t.c, buf); err != nil {
return
}
t.writeLine(t.prompt)
if t.echo {
t.writeLine(t.line)
}
t.moveCursorToPos(t.pos)
if _, err = t.c.Write(t.outBuf); err != nil {
return
}
t.outBuf = t.outBuf[:0]
return
}
// ReadPassword temporarily changes the prompt and reads a password, without
// echo, from the terminal.
func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
t.lock.Lock()
defer t.lock.Unlock()
oldPrompt := t.prompt
t.prompt = []rune(prompt)
t.echo = false
line, err = t.readLine()
t.prompt = oldPrompt
t.echo = true
return
}
// ReadLine returns a line of input from the terminal.
func (t *Terminal) ReadLine() (line string, err error) {
t.lock.Lock()
defer t.lock.Unlock()
return t.readLine()
}
func (t *Terminal) readLine() (line string, err error) {
// t.lock must be held at this point
if t.cursorX == 0 && t.cursorY == 0 {
t.writeLine(t.prompt)
t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
}
lineIsPasted := t.pasteActive
for {
rest := t.remainder
lineOk := false
for !lineOk {
var key rune
key, rest = bytesToKey(rest, t.pasteActive)
if key == utf8.RuneError {
break
}
if !t.pasteActive {
if key == keyCtrlD {
if len(t.line) == 0 {
return "", io.EOF
}
}
if key == keyCtrlC {
return "", io.EOF
}
if key == keyPasteStart {
t.pasteActive = true
if len(t.line) == 0 {
lineIsPasted = true
}
continue
}
} else if key == keyPasteEnd {
t.pasteActive = false
continue
}
if !t.pasteActive {
lineIsPasted = false
}
line, lineOk = t.handleKey(key)
}
if len(rest) > 0 {
n := copy(t.inBuf[:], rest)
t.remainder = t.inBuf[:n]
} else {
t.remainder = nil
}
t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
if lineOk {
if t.echo {
t.historyIndex = -1
t.history.Add(line)
}
if lineIsPasted {
err = ErrPasteIndicator
}
return
}
// t.remainder is a slice at the beginning of t.inBuf
// containing a partial key sequence
readBuf := t.inBuf[len(t.remainder):]
var n int
t.lock.Unlock()
n, err = t.c.Read(readBuf)
t.lock.Lock()
if err != nil {
return
}
t.remainder = t.inBuf[:n+len(t.remainder)]
}
}
// SetPrompt sets the prompt to be used when reading subsequent lines.
func (t *Terminal) SetPrompt(prompt string) {
t.lock.Lock()
defer t.lock.Unlock()
t.prompt = []rune(prompt)
}
func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
// Move cursor to column zero at the start of the line.
t.move(t.cursorY, 0, t.cursorX, 0)
t.cursorX, t.cursorY = 0, 0
t.clearLineToRight()
for t.cursorY < numPrevLines {
// Move down a line
t.move(0, 1, 0, 0)
t.cursorY++
t.clearLineToRight()
}
// Move back to beginning.
t.move(t.cursorY, 0, 0, 0)
t.cursorX, t.cursorY = 0, 0
t.queue(t.prompt)
t.advanceCursor(visualLength(t.prompt))
t.writeLine(t.line)
t.moveCursorToPos(t.pos)
}
func (t *Terminal) SetSize(width, height int) error {
t.lock.Lock()
defer t.lock.Unlock()
if width == 0 {
width = 1
}
oldWidth := t.termWidth
t.termWidth, t.termHeight = width, height
switch {
case width == oldWidth:
// If the width didn't change then nothing else needs to be
// done.
return nil
case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
// If there is nothing on current line and no prompt printed,
// just do nothing
return nil
case width < oldWidth:
// Some terminals (e.g. xterm) will truncate lines that were
// too long when shinking. Others, (e.g. gnome-terminal) will
// attempt to wrap them. For the former, repainting t.maxLine
// works great, but that behaviour goes badly wrong in the case
// of the latter because they have doubled every full line.
// We assume that we are working on a terminal that wraps lines
// and adjust the cursor position based on every previous line
// wrapping and turning into two. This causes the prompt on
// xterms to move upwards, which isn't great, but it avoids a
// huge mess with gnome-terminal.
if t.cursorX >= t.termWidth {
t.cursorX = t.termWidth - 1
}
t.cursorY *= 2
t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
case width > oldWidth:
// If the terminal expands then our position calculations will
// be wrong in the future because we think the cursor is
// |t.pos| chars into the string, but there will be a gap at
// the end of any wrapped line.
//
// But the position will actually be correct until we move, so
// we can move back to the beginning and repaint everything.
t.clearAndRepaintLinePlusNPrevious(t.maxLine)
}
_, err := t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
return err
}
type pasteIndicatorError struct{}
func (pasteIndicatorError) Error() string {
return "terminal: ErrPasteIndicator not correctly handled"
}
// ErrPasteIndicator may be returned from ReadLine as the error, in addition
// to valid line data. It indicates that bracketed paste mode is enabled and
// that the returned line consists only of pasted data. Programs may wish to
// interpret pasted data more literally than typed data.
var ErrPasteIndicator = pasteIndicatorError{}
// SetBracketedPasteMode requests that the terminal bracket paste operations
// with markers. Not all terminals support this but, if it is supported, then
// enabling this mode will stop any autocomplete callback from running due to
// pastes. Additionally, any lines that are completely pasted will be returned
// from ReadLine with the error set to ErrPasteIndicator.
func (t *Terminal) SetBracketedPasteMode(on bool) {
if on {
io.WriteString(t.c, "\x1b[?2004h")
} else {
io.WriteString(t.c, "\x1b[?2004l")
}
}
// stRingBuffer is a ring buffer of strings.
type stRingBuffer struct {
// entries contains max elements.
entries []string
max int
// head contains the index of the element most recently added to the ring.
head int
// size contains the number of elements in the ring.
size int
}
func (s *stRingBuffer) Add(a string) {
if s.entries == nil {
const defaultNumEntries = 100
s.entries = make([]string, defaultNumEntries)
s.max = defaultNumEntries
}
s.head = (s.head + 1) % s.max
s.entries[s.head] = a
if s.size < s.max {
s.size++
}
}
// NthPreviousEntry returns the value passed to the nth previous call to Add.
// If n is zero then the immediately prior value is returned, if one, then the
// next most recent, and so on. If such an element doesn't exist then ok is
// false.
func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
if n < 0 || n >= s.size {
return "", false
}
index := s.head - n
if index < 0 {
index += s.max
}
return s.entries[index], true
}
// readPasswordLine reads from reader until it finds \n or io.EOF.
// The slice returned does not include the \n.
// readPasswordLine also ignores any \r it finds.
// Windows uses \r as end of line. So, on Windows, readPasswordLine
// reads until it finds \r and ignores any \n it finds during processing.
func readPasswordLine(reader io.Reader) ([]byte, error) {
var buf [1]byte
var ret []byte
for {
n, err := reader.Read(buf[:])
if n > 0 {
switch buf[0] {
case '\b':
if len(ret) > 0 {
ret = ret[:len(ret)-1]
}
case '\n':
if runtime.GOOS != "windows" {
return ret, nil
}
// otherwise ignore \n
case '\r':
if runtime.GOOS == "windows" {
return ret, nil
}
// otherwise ignore \r
default:
ret = append(ret, buf[0])
}
continue
}
if err != nil {
if err == io.EOF && len(ret) > 0 {
return ret, nil
}
return ret, err
}
}
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/LICENSE
|
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/codereview.cfg
|
issuerepo: golang/go
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_plan9.go
|
// 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 term
import (
"fmt"
"runtime"
"golang.org/x/sys/plan9"
)
type state struct{}
func isTerminal(fd int) bool {
path, err := plan9.Fd2path(fd)
if err != nil {
return false
}
return path == "/dev/cons" || path == "/mnt/term/dev/cons"
}
func makeRaw(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: MakeRaw not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func getState(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: GetState not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func restore(fd int, state *State) error {
return fmt.Errorf("terminal: Restore not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func getSize(fd int) (width, height int, err error) {
return 0, 0, fmt.Errorf("terminal: GetSize not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func readPassword(fd int) ([]byte, error) {
return nil, fmt.Errorf("terminal: ReadPassword not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
|
term
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/term/term_unix_bsd.go
|
// 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 darwin || dragonfly || freebsd || netbsd || openbsd
package term
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TIOCGETA
const ioctlWriteTermios = unix.TIOCSETA
|
example
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/PATENTS
|
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
example
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/go.mod
|
module golang.org/x/example
go 1.18
require golang.org/x/tools v0.14.0
require (
golang.org/x/mod v0.13.0 // indirect
golang.org/x/sys v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1
)
|
example
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/README.md
|
# Go example projects
[](https://pkg.go.dev/golang.org/x/example)
This repository contains a collection of Go programs and libraries that
demonstrate the language, standard libraries, and tools.
## Clone the project
```
$ git clone https://go.googlesource.com/example
$ cd example
```
https://go.googlesource.com/example is the canonical Git repository.
It is mirrored at https://github.com/golang/example.
## [hello](hello/) and [hello/reverse](hello/reverse/)
```
$ cd hello
$ go build
$ ./hello -help
```
A trivial "Hello, world" program that uses a library package.
The [hello](hello/) command covers:
* The basic form of an executable command
* Importing packages (from the standard library and the local repository)
* Printing strings ([fmt](//golang.org/pkg/fmt/))
* Command-line flags ([flag](//golang.org/pkg/flag/))
* Logging ([log](//golang.org/pkg/log/))
The [reverse](hello/reverse/) reverse covers:
* The basic form of a library
* Conversion between string and []rune
* Table-driven unit tests ([testing](//golang.org/pkg/testing/))
## [helloserver](helloserver/)
```
$ cd helloserver
$ go run .
```
A trivial "Hello, world" web server.
Topics covered:
* Command-line flags ([flag](//golang.org/pkg/flag/))
* Logging ([log](//golang.org/pkg/log/))
* Web servers ([net/http](//golang.org/pkg/net/http/))
## [outyet](outyet/)
```
$ cd outyet
$ go run .
```
A web server that answers the question: "Is Go 1.x out yet?"
Topics covered:
* Command-line flags ([flag](//golang.org/pkg/flag/))
* Web servers ([net/http](//golang.org/pkg/net/http/))
* HTML Templates ([html/template](//golang.org/pkg/html/template/))
* Logging ([log](//golang.org/pkg/log/))
* Long-running background processes
* Synchronizing data access between goroutines ([sync](//golang.org/pkg/sync/))
* Exporting server state for monitoring ([expvar](//golang.org/pkg/expvar/))
* Unit and integration tests ([testing](//golang.org/pkg/testing/))
* Dependency injection
* Time ([time](//golang.org/pkg/time/))
## [appengine-hello](appengine-hello/)
A trivial "Hello, world" App Engine application intended to be used as the
starting point for your own code. Please see
[Google App Engine SDK for Go](https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Go)
and [Quickstart for Go in the App Engine Standard Environment](https://cloud.google.com/appengine/docs/standard/go/quickstart).
## [gotypes](gotypes/)
The `go/types` package is a type-checker for Go programs. It is one of the most
complex packages in Go's standard library, so we have provided this tutorial to
help you find your bearings. It comes with several example programs that you
can obtain using `go get` and play with as you learn to build tools that analyze
or manipulate Go programs.
## [template](template/)
A trivial web server that demonstrates the use of the
[`template` package](https://golang.org/pkg/text/template/)'s `block` feature.
## [slog-handler-guide](slog-handler-guide/)
The `log/slog` package supports structured logging.
It features a flexible backend in the form of a `Handler` interface.
This guide can help you write your own handler.
|
example
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/go.sum
|
golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY=
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc=
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
example
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/LICENSE
|
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
gotypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/Makefile
|
all: README.md
go build ./...
README.md: go-types.md ../internal/cmd/weave/*.go $(wildcard */*.go)
go run ../internal/cmd/weave go-types.md >README.md
# This is for previewing using github.
# $HOME/markdown must be a github client.
test: README.md
cp README.md $$HOME/markdown/
(cd $$HOME/markdown/ && git commit -m . README.md && git push)
|
gotypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/README.md
|
<!-- Autogenerated by weave; DO NOT EDIT -->
# `go/types`: The Go Type Checker
This document is maintained by Alan Donovan `adonovan@google.com`.
[October 2015 GothamGo talk on go/types](https://docs.google.com/presentation/d/13OvHYozAUBeISPRoLgG7kMBuja1NsU1D_mMlmbaYojk/view)
# Contents
1. [Changes in Go 1.18](#changes-in-go-1.18)
1. [Introduction](#introduction)
1. [An Example](#an-example)
1. [Objects](#objects)
1. [Identifier Resolution](#identifier-resolution)
1. [Scopes](#scopes)
1. [Initialization Order](#initialization-order)
1. [Types](#types)
1. [Basic types](#basic-types)
1. [Simple Composite Types](#simple-composite-types)
1. [Struct Types](#struct-types)
1. [Tuple Types](#tuple-types)
1. [Function and Method Types](#function-and-method-types)
1. [Named Types](#named-types)
1. [Interface Types](#interface-types)
1. [TypeAndValue](#typeandvalue)
1. [Selections](#selections)
1. [Ids](#ids)
1. [Method Sets](#method-sets)
1. [Constants](#constants)
1. [Size and Alignment](#size-and-alignment)
1. [Imports](#imports)
1. [Formatting support](#formatting-support)
1. [Getting from A to B](#getting-from-a-to-b)
# Changes in Go 1.18
Go 1.18 introduces generics, and several corresponding new APIs for `go/types`.
This document is not yet up-to-date for these changes, but a guide to the new
changes exists at
[`x/exp/typeparams/example`](https://github.com/golang/exp/tree/master/typeparams/example).
# Introduction
The [`go/types` package]('https://golang.org/pkg/go/types) is a
type-checker for Go programs, designed by Robert Griesemer.
It became part of Go's standard library in Go 1.5.
Measured by lines of code and by API surface area, it is one of the
most complex packages in Go's standard library, and using it requires
a firm grasp of the structure of Go programs.
This tutorial will help you find your bearings.
It comes with several example programs that you can obtain with `go get` and play with.
We assume you are a proficient Go programmer who wants to build tools
to analyze or manipulate Go programs and that you have some knowledge
of how a typical compiler works.
The type checker complements several existing
standard packages for analyzing Go programs.
We've listed them below.
→ go/types
go/constant
go/parser
go/ast
go/scanner
go/token
Starting at the bottom, the
[`go/token` package](http://golang.org/pkg/go/token)
defines the lexical tokens of Go.
The [`go/scanner` package](http://golang.org/pkg/go/scanner) tokenizes an input stream and records
file position information for use in diagnostics
or for file surgery in a refactoring tool.
The [`go/ast` package](http://golang.org/pkg/go/ast)
defines the data types of the abstract syntax tree (AST).
The [`go/parser` package](http://golang.org/pkg/go/parser)
provides a robust recursive-descent parser that constructs the AST.
And [`go/constant`](http://golang.org/pkg/go/constant)
provides representations and arithmetic operations for the values of compile-time
constant expressions, as we'll see in
[Constants](#constants).
The [`golang.org/x/tools/go/packages` package](https://pkg.go.dev/golang.org/x/tools/go/packages)
from the `x/tools` repository is a client of the type
checker that loads, parses, and type-checks a complete Go program from
source code.
We use it in some of our examples and you may find it useful too.
The Go type checker does three main things.
First, for every name in the program, it determines which declaration
the name refers to; this is known as _identifier resolution_.
Second, for every expression in the program, it determines what type
that expression has, or reports an error if the expression has no
type, or has an inappropriate type for its context; this is known as
_type deduction_.
Third, for every constant expression in the program, it determines the
value of that constant; this is known as _constant evaluation_.
Superficially, it appears that these three processes could be done
sequentially, in the order above, but perhaps surprisingly, they must
be done together.
For example, the value of a constant may depend on the type of an
expression due to operators like `unsafe.Sizeof`.
Conversely, the type of an expression may depend on the value of a
constant, since array types contain constants.
As a result, type deduction and constant evaluation must be done
together.
As another example, we cannot resolve the identifier `k` in the composite
literal `T{k: 0}` until we know whether `T` is a struct type.
If it is, then `k` must be found among `T`'s fields.
If not, then `k` is an ordinary reference
to a constant or variable in the lexical environment.
Consequently, identifier resolution and type deduction are also
inseparable in the general case.
Nonetheless, the three processes of identifier resolution, type
deduction, and constant evaluation can be separated for the purpose of
explanation.
# An Example
The code below shows the most basic use of the type checker to check
the _hello, world_ program, supplied as a string.
Later examples will be variations on this one, and we'll often omit
boilerplate details such as parsing.
To check out and build the examples,
run `go get golang.org/x/example/gotypes/...`.
// go get golang.org/x/example/gotypes/pkginfo
```
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}`
func main() {
fset := token.NewFileSet()
// Parse the input string, []byte, or io.Reader,
// recording position information in fset.
// ParseFile returns an *ast.File, a syntax tree.
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
// A Config controls various options of the type checker.
// The defaults work fine except for one setting:
// we must specify how to deal with imports.
conf := types.Config{Importer: importer.Default()}
// Type-check the package containing only file f.
// Check returns a *types.Package.
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
fmt.Printf("Package %q\n", pkg.Path())
fmt.Printf("Name: %s\n", pkg.Name())
fmt.Printf("Imports: %s\n", pkg.Imports())
fmt.Printf("Scope: %s\n", pkg.Scope())
}
```
First, the program creates a
[`token.FileSet`](http://golang.org/pkg/go/token/#FileSet).
To avoid the need to store file names and line and column
numbers in every node of the syntax tree, the `go/token` package
provides `FileSet`, a data structure that stores this information
compactly for a sequence of files.
A `FileSet` records each file name only once, and records
only the byte offsets of each newline, allowing a position within
any file to be identified using a small integer called a
`token.Pos`.
Many tools create a single `FileSet` at startup.
Any part of the program that needs to convert a `token.Pos` into
an intelligible location---as part of an error message, for
instance---must have access to the `FileSet`.
Second, the program parses the input string.
More realistic packages contain several source files, so the parsing
step must be repeated for each one, or better, done in parallel.
Third, it creates a `Config` that specifies type-checking options.
Since the _hello, world_ program uses imports, we must indicate
how to locate the imported packages.
Here we use `importer.Default()`, which loads compiler-generated
export data, but we'll explore alternatives in [Imports](#imports).
Fourth, the program calls `Check`.
This creates a `Package` whose path is `"cmd/hello"`, and
type-checks each of the specified files---just one in this example.
The final (nil) argument is a pointer to an optional `Info`
struct that returns additional deductions from the type checker; more
on that later.
`Check` returns a `Package` even when it also returns an error.
The type checker is robust to ill-formed input,
and goes to great lengths to report accurate
partial information even in the vicinity of syntax or type errors.
`Package` has this definition:
type Package struct{ ... }
func (*Package) Path() string
func (*Package) Name() string
func (*Package) Scope() *Scope
func (*Package) Imports() []*Package
Finally, the program prints the attributes of the package, shown below.
(The hexadecimal number may vary from one run to the next.)
```
$ go build golang.org/x/example/gotypes/pkginfo
$ ./pkginfo
Package "cmd/hello"
Name: main
Imports: [package fmt ("fmt")]
Scope: package "cmd/hello" scope 0x820533590 {
. func cmd/hello.main()
}
```
A package's `Path`, such as `"encoding/json"`, is the string
by which import declarations identify it.
It is unique within a `$GOPATH` workspace,
and for published packages it must be globally unique.
A package's `Name` is the identifier in the `package`
declaration of each source file within the package, such as `json`.
The type checker reports an error if not all the package declarations in
the package agree.
The package name determines how the package is known when it is
imported into a file (unless a renaming import is used),
but is otherwise not visible to a program.
`Scope` returns the package's [_lexical block_](#scopes),
which provides access to all the named entities or
[_objects_](#objects) declared at package level.
`Imports` returns the set of packages directly imported by this
one, and may be useful for computing dependencies
([Initialization Order](#initialization-order)).
# Objects
The task of identifier resolution is to map every identifier in the
syntax tree, that is, every `ast.Ident`, to an object.
For our purposes, an _object_ is a named entity created by a
declaration, such as a `var`, `type`, or `func`
declaration.
(This is different from the everyday meaning of object in
object-oriented programming.)
Objects are represented by the `Object` interface:
type Object interface {
Name() string // package-local object name
Exported() bool // reports whether the name starts with a capital letter
Type() Type // object type
Pos() token.Pos // position of object identifier in declaration
Parent() *Scope // scope in which this object is declared
Pkg() *Package // nil for objects in the Universe scope and labels
Id() string // object id (see Ids section below)
}
The first four methods are straightforward; we'll explain the other
three later.
`Name` returns the object's name---an identifier.
`Exported` is a convenience method that reports whether the first
letter of `Name` is a capital, indicating that the object may be
visible from outside the package.
It's a shorthand for `ast.IsExported(obj.Name())`.
`Type` returns the object's type; we'll come back to that in
[Types](#types).
`Pos` returns the source position of the object's declaring identifier.
To make sense of a `token.Pos`, we need to call the
`(*token.FileSet).Position` method, which returns a struct with
individual fields for the file name, line number, column, and byte
offset, though usually we just call its `String` method:
fmt.Println(fset.Position(obj.Pos())) // "hello.go:10:6"
Not all objects carry position information.
Since the file format for compiler export data ([Imports](#imports))
does not record position information, calling `Pos` on an object
imported from such a file returns zero, also known as
`token.NoPos`.
There are eight kinds of objects in the Go type checker.
Most familiar are the kinds that can be declared at package level:
constants, variables, functions, and types.
Less familiar are statement labels, imported package names
(such as `json` in a file containing an `import "encoding/json"`
declaration), built-in functions (such as `append` and
`len`), and the pre-declared `nil`.
The eight types shown below are the only concrete types that satisfy
the `Object` interface.
In other words, `Object` is a _discriminated union_ of 8
possible types, and we commonly use a type switch to distinguish them.
Object = *Func // function, concrete method, or abstract method
| *Var // variable, parameter, result, or struct field
| *Const // constant
| *TypeName // type name
| *Label // statement label
| *PkgName // package name, e.g. json after import "encoding/json"
| *Builtin // predeclared function such as append or len
| *Nil // predeclared nil
`Object`s are canonical.
That is, two `Object`s `x` and `y` denote the same
entity if and only if `x==y`.
Object identity is significant, and objects are routinely compared by
the addresses of the underlying pointers.
Although a package-level object is uniquely identified by its name
and enclosing package, for other objects there is no simple way to
obtain a string that uniquely identifies it.
The `Parent` method returns the `Scope` (lexical block) in
which the object was declared; we'll come back to this in
[Scopes](#scopes).
Fields and methods are not found in the lexical environment, so
their objects have no `Parent`.
<!-- TODO check this -->
The `Pkg` method returns the `Package` to which this object
belongs, even for objects not declared at package level.
Only predeclared objects have no package.
The `Id` method will be explained in [Ids](#ids).
Not all methods make sense for each kind of object. For instance,
the last four kinds above have no meaningful `Type` method.
And some kinds of objects have methods in addition to those required by the
`Object` interface:
func (*Func) Scope() *Scope
func (*Var) Anonymous() bool
func (*Var) IsField() bool
func (*Const) Val() constant.Value
func (*TypeName) IsAlias() bool
func (*PkgName) Imported() *Package
`(*Func).Scope` returns the [lexical block](#scopes)
containing the function's parameters, results,
and other local declarations.
`(*Var).IsField` distinguishes struct fields from ordinary
variables, and `(*Var).Anonymous` discriminates named fields like
the one in `struct{T T}` from anonymous fields like the one in `struct{T}`.
`(*Const).Val` returns the value of a named [constant](#constants).
`(*TypeName).IsAlias`, introduced in Go 1.9, reports whether the
type name is simply an alias for a type (as in `type I = int`),
as opposed to a definition of a [`Named`](#named-types) type, as
in `type Celsius float64`.
`(*PkgName).Imported` returns the package (for instance,
`encoding/json`) denoted by a given import name such as `json`.
Each time a package is imported, a new `PkgName` object is
created, usually with the same name as the `Package` it
denotes, but not always, as in the case of a renaming import.
`PkgName`s are objects, but `Package`s are not.
We'll look more closely at this in [Imports](#imports).
All relationships between the syntax trees (`ast.Node`s) and type
checker data structures such as `Object`s and `Type`s are
stored in mappings outside the syntax tree itself.
Be aware that the `go/ast` package also defines a type called
`Object` that resembles---and predates---the type checker's
`Object`, and that `ast.Object`s are held directly by
identifiers in the AST.
They are created by the parser, which has a necessarily limited view
of the package, so the information they represent is at best partial and
in some cases wrong, as in the `T{k: 0}` example mentioned above.
If you are using the type checker, there is no reason to use the older
`ast.Object` mechanism.
# Identifier Resolution
Identifier resolution computes the relationship between
identifiers and objects.
Its results are recorded in the `Info` struct optionally passed
to `Check`.
The fields related to identifier resolution are shown below.
type Info struct {
Defs map[*ast.Ident]Object
Uses map[*ast.Ident]Object
Implicits map[ast.Node]Object
Selections map[*ast.SelectorExpr]*Selection
Scopes map[ast.Node]*Scope
...
}
Since not all facts computed by the type checker are needed by every
client, the API lets clients control which components of the result
should be recorded and which discarded: only fields that hold a
non-nil map will be populated during the call to `Check`.
The two fields of type `map[*ast.Ident]Object` are the most important:
`Defs` records _declaring_ identifiers and
`Uses` records _referring_ identifiers.
In the example below, the comments indicate which identifiers are of
which kind.
var x int // def of x, use of int
fmt.Println(x) // uses of fmt, Println, and x
type T struct{U} // def of T, use of U (type), def of U (field)
The final line above illustrates why we don't combine `Defs` and
`Uses` into one map.
In the anonymous field declaration `struct{U}`, the
identifier `U` is both a use of the type `U` (a
`TypeName`) and a definition of the anonymous field (a
`Var`).
The function below prints the location of each referring and defining
identifier in the input program, and the object it refers to.
// go get golang.org/x/example/gotypes/defsuses
```
func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
_, err := conf.Check("hello", fset, files, info)
if err != nil {
return err // type error
}
for id, obj := range info.Defs {
fmt.Printf("%s: %q defines %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
for id, obj := range info.Uses {
fmt.Printf("%s: %q uses %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
return nil
}
```
Let's use the _hello, world_ program again as the input:
// go get golang.org/x/example/gotypes/hello
```
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
```
This is what it prints:
```
$ go build golang.org/x/example/gotypes/defsuses
$ ./defsuses
hello.go:1:9: "main" defines <nil>
hello.go:5:6: "main" defines func hello.main()
hello.go:6:9: "fmt" uses package fmt
hello.go:6:13: "Println" uses func fmt.Println(a ...interface{}) (n int, err error)
```
Notice that the `Defs` mapping may contain nil entries in a few
cases.
The first line of output reports that the package identifier
`main` is present in the `Defs` mapping, but has no
associated object.
The `Implicits` mapping handles two cases of the syntax in
which an `Object` is declared without an `ast.Ident`, namely type
switches and import declarations.
<!--
A third case: an anonymous function parameter or result variable.
These objects are returned by Signature.Param and Signature.Result.
-->
In the type switch below, which declares a local variable `y`,
the type of `y` is different in each case of the switch:
switch y := x.(type) {
case int:
fmt.Printf("%d", y)
case string:
fmt.Printf("%q", y)
default:
fmt.Print(y)
}
To represent this, for each single-type case, the type checker creates
a separate `Var` object for `y` with the appropriate type,
and `Implicits` maps each `ast.CaseClause` to the `Var`
for that case.
The `default` case, the `nil` case, and cases with more than one
type all use the regular `Var` object that is associated with the
identifier `y`, which is found in the `Defs` mapping.
The import declaration below defines the name `json` without an
`ast.Ident`:
import "encoding/json"
`Implicits` maps this `ast.ImportSpec` to the `PkgName`
object named `json` that it implicitly declares.
The `Selections` mapping, of type
`map[*ast.SelectorExpr]*Selection`, records the meaning of each
expression of the form _`expr`_`.f`, where _`expr`_ is
an expression or type and `f` is the name of a field or method.
These expressions, called _selections_, are represented by
`ast.SelectorExpr` nodes in the AST.
We'll talk more about the `Selection` type in [Selections](#selections).
Not all `ast.SelectorExpr` nodes represent selections.
Expressions like `fmt.Println`, in which a package name precedes
the dot, are _qualified identifiers_.
They do not appear in the `Selections` mapping, but their
constituent identifiers (such as `fmt` and `Println`) both
appear in `Uses`.
Referring identifiers that are not part of an `ast.SelectorExpr`
are _lexical references_.
That is, they are resolved to an object by searching for the
innermost enclosing lexical declaration of that name.
We'll see how that search works in the next section.
# Scopes
The `Scope` type is a mapping from names to objects.
type Scope struct{ ... }
func (s *Scope) Names() []string
func (s *Scope) Lookup(name string) Object
`Names` returns the set of names in the mapping, in sorted order.
(It is not a simple accessor though, so call it sparingly.)
The `Lookup ` method returns the object for a given name, so we
can print all the entries or _bindings_ in a scope like this:
for _, name := range scope.Names() {
fmt.Println(scope.Lookup(name))
}
The _scope_ of a declaration of a name is the region of
program source in which a reference to the name resolves to that
declaration. That is, scope is a property of a declaration.
However, in the `go/types` API, the `Scope` type represents
a _lexical block_, which is one component of the lexical
environment.
Consider the _hello, world_ program again:
package main
import "fmt"
func main() {
const message = "hello, world"
fmt.Println(message)
}
There are four lexical blocks in this program.
The outermost one is the _universe block_, which maps the
pre-declared names like `int`, `true`, and `append` to
their objects---a `TypeName`, a `Const`, and a
`Builtin`, respectively.
The universe block is represented by the global variable
`Universe`, of type `*Scope`, although it's logically a
constant so you shouldn't modify it.
Next is the _package block_, which maps `"main"` to the
`main` function.
Following that is the _file block_, which maps `"fmt"` to
the `PkgName` object for this import of the `fmt` package.
And finally, the innermost block is that of function `main`, a
local block, which contains the declaration of `message`, a `Const`.
The `main` function is trivial, but many functions contain
several blocks since each `if`, `for`, `switch`,
`case`, or `select` statement creates at least one
additional block.
Local blocks nest to arbitrary depths.
The structure of the lexical environment thus forms a tree, with the
universe block at the root, the package blocks beneath it, the file
blocks beneath them, and then any number of local blocks beneath the
files.
We can access and navigate this tree structure with the following
methods of `Scope`:
func (s *Scope) Parent() *Scope
func (s *Scope) NumChildren() int
func (s *Scope) Child(i int) *Scope
`Parent` lets us walk up the tree, and `Child`
lets us walk down it.
Note that although the `Parent` of every package `Scope` is
`Universe`, `Universe` has no children.
This asymmetry is a consequence of using a global variable to hold
`Universe`.
To obtain the universe block, we use the `Universe` global variable.
To obtain the lexical block of a `Package`, we call its
`Scope` method.
To obtain the scope of a file (`*ast.File`), or any smaller piece
of syntax such as an `*ast.IfStmt`, we consult the `Scopes`
mapping in the `Info` struct, which maps each block-creating
syntax node to its block.
The lexical block of a named function or method can also be obtained
by calling its `(*Func).Scope` method.
<!--
TODO: explain explicit and implicit blocks
TODO: explain Dot imports.
TODO: explain that Func blocks are associated with FuncType (not FuncDecl or FuncLit)
-->
To look up a name in the lexical environment, we must search the tree
of lexical blocks, starting at a particular `Scope` and walking
up to the root until a declaration of the name is found.
For convenience, the `LookupParent` method does this, returning
not just the object, if found, but also the `Scope` in which it was
declared, which may be an ancestor of the initial one:
func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)
The `pos` parameter determines the position in the source code at
which the name should be resolved.
The effective lexical environment is different at each point in the
block because it depends on which local declarations appear
before or after that point.
(We'll see an illustration in a moment.)
`Scope` has several other methods relating to source positions:
func (s *Scope) Pos() token.Pos
func (s *Scope) End() token.Pos
func (s *Scope) Contains(pos token.Pos) bool
func (s *Scope) Innermost(pos token.Pos) *Scope
`Pos` and `End` report the `Scope`'s start and end
position which, for explicit blocks, coincide with its curly
braces.
`Contains` is a convenience method that reports whether a
position lies in this interval.
`Innermost` returns the innermost scope containing the specified
position, which may be a child or other descendent of the initial
scope.
These features are useful for tools that wish to resolve names or
evaluate constant expressions as if they had appeared at a particular
point within the program.
The next example program finds all the comments in the input,
treating the contents of each one as a name. It looks up each name in
the environment at the position of the comment, and prints what it
finds.
Observe that the `ParseComments` flag directs the parser to
preserve comments in the input.
// go get golang.org/x/example/gotypes/lookup
```
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
// Each comment contains a name.
// Look up that name in the innermost scope enclosing the comment.
for _, comment := range f.Comments {
pos := comment.Pos()
name := strings.TrimSpace(comment.Text())
fmt.Printf("At %s,\t%q = ", fset.Position(pos), name)
inner := pkg.Scope().Innermost(pos)
if _, obj := inner.LookupParent(name, pos); obj != nil {
fmt.Println(obj)
} else {
fmt.Println("not found")
}
}
}
```
The expression `pkg.Scope().Innermost(pos)` finds the innermost
`Scope` that encloses the comment, and `LookupParent(name, pos)`
does a name lookup at a specific position in that lexical block.
A typical input is shown below.
The first comment causes a lookup of `"append"` in the file block.
The second comment looks up `"fmt"` in the `main` function's block,
and so on.
```
const hello = `
package main
import "fmt"
// append
func main() {
// fmt
fmt.Println("Hello, world")
// main
main, x := 1, 2
// main
print(main, x)
// x
}
// x
`
```
Here's the output:
```
$ go build golang.org/x/example/gotypes/lookup
$ ./lookup
At hello.go:6:1, "append" = builtin append
At hello.go:8:9, "fmt" = package fmt
At hello.go:10:9, "main" = func cmd/hello.main()
At hello.go:12:9, "main" = var main int
At hello.go:14:9, "x" = var x int
At hello.go:16:1, "x" = not found
```
Notice how the two lookups of `main` return different results,
even though they occur in the same block, because one precedes the
declaration of the local variable named `main` and the other
follows it.
Also notice that there are two lookups of the name `x` but only
the first one, in the function block, succeeds.
Download the program and modify both the input program and
the set of comments to get a better feel for how name resolution works.
The table below summarizes which kinds of objects may be declared at
each level of the tree of lexical blocks.
Universe File Package Local
Builtin ✔
Nil ✔
Const ✔ ✔ ✔
TypeName ✔ ✔ ✔
Func ✔
Var ✔ ✔
PkgName ✔
Label ✔
# Initialization Order
In the course of identifier resolution, the type checker constructs a
graph of references among declarations of package-level variables and
functions.
The type checker reports an error if the initializer expression for a
variable refers to that variable, whether directly or indirectly.
The reference graph determines the initialization order of the
package-level variables, as required by the Go spec, using a
breadth-first algorithm.
First, variables in the graph with no successors are removed, sorted
into the order in which they appear in the source code, then added
to a list. This creates more variables that have no successors.
The process repeats until they have all been removed.
The result is available in the `InitOrder` field of the
`Info` struct, whose type is `[]Initializer`.
type Info struct {
...
InitOrder []Initializer
...
}
type Initializer struct {
Lhs []*Var // var Lhs = Rhs
Rhs ast.Expr
}
Each element of the list represents a single initializer expression
that must be executed, and the variables to which it is assigned.
The variables may number zero, one, or more, as in these examples:
var _ io.Writer = new(bytes.Buffer)
var rx = regexp.MustCompile("^b(an)*a$")
var cwd, cwdErr = os.Getwd()
This process governs the initialization order of variables within a
package.
Across packages, dependencies must be initialized first, although the
order among them is not specified.
That is, any topological order of the import graph will do.
The `(*Package).Imports` method returns the set of direct
dependencies of a package.
# Types
The main job of the type checker is, of course, to deduce the type
of each expression and to report type errors.
Like `Object`, `Type` is an interface type used as a
discriminated union of several concrete types but, unlike
`Object`, `Type` has very few methods because types have
little in common with each other.
Here is the interface:
type Type interface {
Underlying() Type
}
And here are the eleven concrete types that satisfy it:
Type = *Basic
| *Pointer
| *Array
| *Slice
| *Map
| *Chan
| *Struct
| *Tuple
| *Signature
| *Named
| *Interface
With the exception of `Named` types, instances of `Type` are
not canonical.
That is, it is usually a mistake to compare types using `t1==t2`
since this equivalence is not the same as the
[type identity relation](https://golang.org/ref/spec#Type_identity)
defined by the Go spec.
Use this function instead:
func Identical(t1, t2 Type) bool
For the same reason, you should not use a `Type` as a key in a map.
The [`golang.org/x/tools/go/types/typeutil` package](https://pkg.go.dev/golang.org/x/tools/go/types/typeutil)
provides a map keyed by types that uses the correct
equivalence relation.
The Go spec defines three relations over types.
[_Assignability_](https://golang.org/ref/spec#Assignability)
governs which pairs of types may appear on the
left- and right-hand side of an assignment, including implicit
assignments such as function calls, map and channel operations, and so
on.
[_Comparability_](https://golang.org/ref/spec#Comparison_operators)
determines which types may appear in a comparison `x==y` or a
switch case or may be used as a map key.
[_Convertibility_](https://golang.org/ref/spec#Conversions)
governs which pairs of types are allowed in a conversion operation
`T(v)`.
You can query these relations with the following predicate functions:
func AssignableTo(V, T Type) bool
func Comparable(T Type) bool
func ConvertibleTo(V, T Type) bool
Let's take a look at each kind of type.
## Basic types
`Basic` represents all types that are not composed from simpler
types.
This is essentially the set of underlying types that a constant expression is
permitted to have--strings, booleans, and numbers---but it also
includes `unsafe.Pointer` and untyped nil.
type Basic struct{...}
func (*Basic) Kind() BasicKind
func (*Basic) Name() string
func (*Basic) Info() BasicInfo
The `Kind` method returns an "enum" value that indicates which
basic type this is.
The kinds `Bool`, `String`, `Int16`, and so on,
represent the corresponding predeclared boolean, string, or numeric
types.
There are two synonyms: `Byte` is equivalent to `Uint8`
and `Rune` is equivalent to `Int32`.
The kind `UnsafePointer` represents `unsafe.Pointer`.
The kinds `UntypedBool`, `UntypedInt` and so on represent
the six kinds of "untyped" constant types: boolean, integer, rune,
float, complex, and string.
The kind `UntypedNil` represents the type of the predeclared
`nil` value.
And the kind `Invalid` indicates the invalid type, which is used
for expressions containing errors, or for objects without types, like
`Label`, `Builtin`, or `PkgName`.
The `Name` method returns the name of the type, such as
`"float64"`, and the `Info` method returns a bitfield that
encodes information about the type, such as whether it is signed or
unsigned, integer or floating point, or real or complex.
`Typ` is a table of canonical basic types, indexed by
kind, so `Typ[String]` returns the `*Basic` that represents
`string`, for instance.
Like `Universe`, `Typ` is logically a constant, so don't
modify it.
A few minor subtleties:
According to the Go spec, pre-declared types such as `int` are
named types for the purposes of assignability, even though the type
checker does not represent them using `Named`.
And `unsafe.Pointer` is a pointer type for the purpose of
determining whether the receiver type of a method is legal, even
though the type checker does not represent it using `Pointer`.
The "untyped" types are usually only ascribed to constant expressions,
but there is one exception.
A comparison `x==y` has type "untyped bool", so the result of
this expression may be assigned to a variable of type `bool` or
any other named boolean type.
## Simple Composite Types
The types `Pointer`, `Array`, `Slice`, `Map`,
and `Chan` are pretty self-explanatory.
All have an `Elem` method that returns the element type `T`
for a pointer `*T`, an array `[n]T`, a slice `[]T`, a
map `map[K]T`, or a channel `chan T`.
This should feel familiar if you've used the `reflect.Value` API.
In addition, the `*Map`, `*Chan`, and `*Array` types
have accessor methods that return their key type, direction, and
length, respectively:
func (*Map) Key() Type
func (*Chan) Dir() ChanDir // = Send | Recv | SendRecv
func (*Array) Len() int64
## Struct Types
A struct type has an ordered list of fields and a corresponding
ordered list of field tags.
type Struct struct{ ... }
func (*Struct) NumFields() int
func (*Struct) Field(i int) *Var
func (*Struct) Tag(i int) string
Each field is a `Var` object whose `IsField` method returns true.
Field objects have no `Parent` scope, because they are
resolved through selections, not through the lexical environment.
<!-- TODO check this -->
Thanks to embedding, the expression `new(S).f` may be a shorthand
for a longer expression such as `new(S).d.e.f`, but in the
representation of `Struct` types, these field selection
operations are explicit.
That is, the set of fields of struct type `S` does not include `f`.
An anonymous field is represented like a regular field, but its
`Anonymous` method returns true.
One subtlety is relevant to tools that generate documentation.
When analyzing a declaration such as this,
type T struct{x int}
it may be tempting to consider the `Var` object for field `x` as if it
had the name `"T.x"`, but beware: field objects do not have
canonical names and there is no way to obtain the name `"T"`
from the `Var` for `x`.
That's because several types may have the same underlying struct type,
as in this code:
type T struct{x int}
type U T
Here, the `Var` for field `x` belongs equally to `T`
and to `U`, and short of inspecting source positions or walking
the AST---neither of which is possible for objects loaded from compiler
export data---it is not possible to ascertain that `x` was declared as
part of `T`.
The type checker builds the exact same data structures given this input:
type T U
type U struct{x int}
A similar issue applies to the methods of named interface types.
## Tuple Types
Like a struct, a tuple type has an ordered list of fields, and fields
may be named.
type Tuple struct{ ... }
func (*Tuple) Len() int
func (*Tuple) At(i int) *Var
Although tuples are not the type of any variable in Go, they are
the type of some expressions, such as the right-hand sides of these
assignments:
v, ok = m[key]
v, ok = <-ch
v, ok = x.(T)
f, err = os.Open(filename)
Tuples also represent the types of the parameter list and the result
list of a function, as we will see.
Since empty tuples are common, the nil `*Tuple` pointer is a valid empty tuple.
## Function and Method Types
The types of functions and methods are represented by a `Signature`,
which has a tuple of parameter types and a tuple of result types.
type Signature struct{ ... }
func (*Signature) Recv() *Var
func (*Signature) Params() *Tuple
func (*Signature) Results() *Tuple
func (*Signature) Variadic() bool
Variadic functions such as `fmt.Println` have the `Variadic`
flag set.
The final parameter of such functions is always a slice, or in the
special case of certain calls to `append`, a string.
A `Signature` for a method, whether concrete or abstract, has a
non-nil receiver parameter, `Recv`.
The type of the receiver is usually a named type or a pointer to a named type,
but it may be an unnamed struct or interface type in some cases.
Method types are rather second-class: they are only used for the
`Func` objects created by method declarations, and no Go
expression has a method type.
When printing a method type, the receiver does not appear, and the
`Identical` predicate ignores the receiver.
The types of `Builtin` objects like `append` cannot be
expressed as a `Signature` since those types require parametric
polymorphism.
`Builtin` objects are thus ascribed the `Invalid` basic type.
However, the type of each _call_ to a built-in function has a specific
and expressible Go type.
These types are recorded during type checking for later use
([TypeAndValue](#typeandvalue)).
## Named Types
Type declarations come in two forms.
The simplest kind, introduced in Go 1.9,
merely declares a (possibly alternative) name for an existing type.
Type names used in this way are informally called _type aliases_.
For example, this declaration lets you use the type
`Dictionary` as an alias for `map[string]string`:
type Dictionary = map[string]string
The declaration creates a `TypeName` object for `Dictionary`. The
object's `IsAlias` method returns true, and its `Type` method returns
a `Map` type that represents `map[string]string`.
The second form of type declaration, and the only kind prior to Go
1.9, does not use an equals sign:
type Celsius float64
This declaration does more than just give a name to a type.
It first defines a new `Named` type
whose underlying type is `float64`; this `Named` type is different
from any other type, including `float64`. The declaration binds the
`TypeName` object to the `Named` type.
Since Go 1.9, the Go language specification has used the term _defined
types_ instead of named types;
the essential property of a defined type is not that it has a name,
but that it is a distinct type with its own method set.
However, the type checker API predates that
change and instead calls defined types "named" types.
type Named struct{ ... }
func (*Named) NumMethods() int
func (*Named) Method(i int) *Func
func (*Named) Obj() *TypeName
func (*Named) Underlying() Type
The `Named` type's `Obj` method returns the `TypeName` object, which
provides the name, position, and other properties of the declaration.
Conversely, the `TypeName` object's `Type` method returns the `Named` type.
A `Named` type may appear as the receiver type in a method declaration.
Methods are associated with the `Named` type, not the name (the
`TypeName` object); it's possible---though cryptic---to declare a
method on a `Named` type using one of its aliases.
The `NumMethods` and `Method` methods enumerate the declared
methods associated with this `Named` type (or a pointer to it),
in the order they were declared.
However, due to the subtleties of anonymous fields and the difference
between value and pointer receivers, a named type may have more or fewer
methods than this list. We'll return to this in [Method Sets](#method-sets).
Every `Type` has an `Underlying` method, but for all of them
except `*Named`, it is simply the identity function.
For a named type, `Underlying` returns its underlying type, which
is always an unnamed type.
Thus `Underlying` returns `int` for both `T` and
`U` below.
type T int
type U T
Clients of the type checker often use type assertions or type switches
with a `Type` operand.
When doing so, it is often necessary to switch on the type that
_underlies_ the type of interest, and failure to do so may be a
bug.
This is a common pattern:
// handle types of composite literal
switch u := t.Underlying().(type) {
case *Struct: // ...
case *Map: // ...
case *Array, *Slice: // ...
default:
panic("impossible")
}
## Interface Types
Interface types are represented by `Interface`.
type Interface struct{ ... }
func (*Interface) Empty() bool
func (*Interface) NumMethods() int
func (*Interface) Method(i int) *Func
func (*Interface) NumEmbeddeds() int
func (*Interface) Embedded(i int) *Named
func (*Interface) NumExplicitMethods() int
func (*Interface) ExplicitMethod(i int) *Func
Syntactically, an interface type has a list of explicitly declared
methods (`ExplicitMethod`), and a list of embedded named
interface types (`Embedded`), but many clients care only about
the complete set of methods, which can be enumerated via
`Method`.
All three lists are ordered by name.
Since the empty interface is an important special case, the
`Empty` predicate provides a shorthand for `NumMethods() ==
0`.
As with the fields of structs (see above), the methods of interfaces
may belong equally to more than one interface type.
The `Func` object for method `f` in the code below is shared
by `I` and `J`:
type I interface { f() }
type J I
Because the difference between interface (abstract) and
non-interface (concrete) types is so important in Go, the
`IsInterface` predicate is provided for convenience.
func IsInterface(Type) bool
The type checker provides three utility methods relating to interface
satisfaction:
func Implements(V Type, T *Interface) bool
func AssertableTo(V *Interface, T Type) bool
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
The `Implements` predicate reports whether a type satisfies an
interface type.
`MissingMethod` is like `Implements`, but instead of
returning false, it explains why a type does not satisfy the
interface, for use in diagnostics.
`AssertableTo` reports whether a type assertion `v.(T)` is legal.
If `T` is a concrete type that doesn't have all the methods of
interface `v`, then the type assertion is not legal, as in this example:
// error: io.Writer is not assertible to int
func f(w io.Writer) int { return w.(int) }
## TypeAndValue
The type checker records the type of each expression in another field
of the `Info` struct, namely `Types`:
type Info struct {
...
Types map[ast.Expr]TypeAndValue
}
No entries are recorded for identifiers since the `Defs` and
`Uses` maps provide more information about them.
Also, no entries are recorded for pseudo-expressions like
`*ast.KeyValuePair` or `*ast.Ellipsis`.
The value of the `Types` map is a `TypeAndValue`, which
(unsurprisingly) holds the type and value of the expression, and in
addition, its _mode_.
The mode is opaque, but has predicates to answer questions such as:
Does this expression denote a value or a type? Does this value have an
address? Does this expression appear on the left-hand side of an
assignment? Does this expression appear in a context that expects two
results?
The comments in the code below give examples of expressions that
satisfy each predicate.
type TypeAndValue struct {
Type Type
Value constant.Value // for constant expressions only
...
}
func (TypeAndValue) IsVoid() bool // e.g. "main()"
func (TypeAndValue) IsType() bool // e.g. "*os.File"
func (TypeAndValue) IsBuiltin() bool // e.g. "len(x)"
func (TypeAndValue) IsValue() bool // e.g. "*os.Stdout"
func (TypeAndValue) IsNil() bool // e.g. "nil"
func (TypeAndValue) Addressable() bool // e.g. "a[i]" but not "f()", "m[key]"
func (TypeAndValue) Assignable() bool // e.g. "a[i]", "m[key]"
func (TypeAndValue) HasOk() bool // e.g. "<-ch", "m[key]"
The statement below inspects every expression within the AST of a single
type-checked file and prints its type, value, and mode:
// go get golang.org/x/example/gotypes/typeandvalue
```
// f is a parsed, type-checked *ast.File.
ast.Inspect(f, func(n ast.Node) bool {
if expr, ok := n.(ast.Expr); ok {
if tv, ok := info.Types[expr]; ok {
fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv))
fmt.Printf("\t\t\t\ttype: %v\n", tv.Type)
if tv.Value != nil {
fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value)
}
}
}
return true
})
```
It makes use of these two helper functions, which are not shown:
// nodeString formats a syntax tree in the style of gofmt.
func nodeString(n ast.Node) string
// mode returns a string describing the mode of an expression.
func mode(tv types.TypeAndValue) string
Given this input:
```
const input = `
package main
var m = make(map[string]int)
func main() {
v, ok := m["hello, " + "world"]
print(rune(v), ok)
}
`
```
the program prints:
```
$ go build golang.org/x/example/gotypes/typeandvalue
$ ./typeandvalue
make(map[string]int) mode: value
type: map[string]int
make mode: builtin
type: func(map[string]int) map[string]int
map[string]int mode: type
type: map[string]int
string mode: type
type: string
int mode: type
type: int
m["hello, "+"world"] mode: value,assignable,ok
type: (int, bool)
m mode: value,addressable,assignable
type: map[string]int
"hello, " + "world" mode: value
type: string
value: "hello, world"
"hello, " mode: value
type: untyped string
value: "hello, "
"world" mode: value
type: untyped string
value: "world"
print(rune(v), ok) mode: void
type: ()
print mode: builtin
type: func(rune, bool)
rune(v) mode: value
type: rune
rune mode: type
type: rune
...more not shown...
```
Notice that the identifiers for the built-ins `make` and
`print` have types that are specific to the particular calls in
which they appear.
Also notice `m["hello"]` has a 2-tuple type `(int, bool)`
and that it is assignable, but unlike the variable `m`, it is not
addressable.
Download the example and vary the inputs and see what the program prints.
Here's another example, adapted from the `govet` static checking tool.
It checks for accidental uses of a method value `x.f` when a
call `x.f()` was intended;
comparing a method `x.f` against nil is a common mistake.
// go get golang.org/x/example/gotypes/nilfunc
```
// CheckNilFuncComparison reports unintended comparisons
// of functions against nil, e.g., "if x.Method == nil {".
func CheckNilFuncComparison(info *types.Info, n ast.Node) {
e, ok := n.(*ast.BinaryExpr)
if !ok {
return // not a binary operation
}
if e.Op != token.EQL && e.Op != token.NEQ {
return // not a comparison
}
// If this is a comparison against nil, find the other operand.
var other ast.Expr
if info.Types[e.X].IsNil() {
other = e.Y
} else if info.Types[e.Y].IsNil() {
other = e.X
} else {
return // not a comparison against nil
}
// Find the object.
var obj types.Object
switch v := other.(type) {
case *ast.Ident:
obj = info.Uses[v]
case *ast.SelectorExpr:
obj = info.Uses[v.Sel]
default:
return // not an identifier or selection
}
if _, ok := obj.(*types.Func); !ok {
return // not a function or method
}
fmt.Printf("%s: comparison of function %v %v nil is always %v\n",
fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)
}
```
Given this input,
```
const input = `package main
import "bytes"
func main() {
var buf bytes.Buffer
if buf.Bytes == nil && bytes.Repeat != nil && main == nil {
// ...
}
}
`
```
the program reports these errors:
```
$ go build golang.org/x/example/gotypes/nilfunc
$ ./nilfunc
input.go:7:5: comparison of function Bytes == nil is always false
input.go:7:25: comparison of function Repeat != nil is always true
input.go:7:48: comparison of function main == nil is always false
```
# Selections
A _selection_ is an expression _`expr`_`.f` in which
`f` denotes either a struct field or a method.
A selection is resolved not by looking for a name in the lexical
environment, but by looking within a _type_.
The type checker ascertains the meaning of each selection in the
package---a surprisingly tricky business---and records it in the
`Selections` mapping of the `Info` struct, whose values are
of type `Selection`:
type Selection struct{ ... }
func (s *Selection) Kind() SelectionKind // = FieldVal | MethodVal | MethodExpr
func (s *Selection) Recv() Type
func (s *Selection) Obj() Object
func (s *Selection) Type() Type
func (s *Selection) Index() []int
func (s *Selection) Indirect() bool
The `Kind` method discriminates between the three (legal) kinds
of selections, as indicated by the comments below.
type T struct{Field int}
func (T) Method() {}
var v T
// Kind Type
var _ = v.Field // FieldVal int
var _ = v.Method // MethodVal func()
var _ = T.Method // MethodExpr func(T)
Because of embedding, a selection may denote more than one field or
method, in which case it is ambiguous, and no `Selection` is
recorded for it.
The `Obj` method returns the `Object` for the selected field
(`*Var`) or method (`*Func`).
Due to embedding, the object may belong to a different type than that
of the receiver expression _`expr`_.
The `Type` method returns the type of the selection. For a field
selection, this is the type of the field, but for method selections,
the result is a function type that is not the same as the type of the
method.
For a `MethodVal`, the receiver parameter is dropped, and
for a `MethodExpr`, the receiver parameter becomes a regular
parameter, as shown in the example above.
The `Index` and `Indirect` methods report information about
implicit operations occurring during the selection that a compiler
would need to know about.
Because of embedding, a selection _`expr`_`.f` may be
shorthand for a sequence containing several implicit field selections,
_`expr`_`.d.e.f`, and `Index` reports the complete
sequence.
And because of automatic pointer dereferencing during struct field
accesses and method calls, a selection may imply one or more indirect
loads from memory; `Indirect` reports whether this occurs.
Clients of the type checker can call `LookupFieldOrMethod` to
look up a name within a type, as if by a selection.
This function has an intimidating signature, but conceptually it
accepts just a `Type` and a name, and returns a `Selection`:
func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) \
(obj Object, index []int, indirect bool)
The result is not actually a `Selection`, but it contains the
three main components of one: `Obj`, `Index`,
and `Indirect`.
The `addressable` flag should be set if the receiver is a
_variable_ of type `T`, since in a method selection on a
variable, an implicit address-of operation (`&`) may occur.
The flag indicates whether the methods of type `*T` should be
considered during the lookup.
(You may wonder why this parameter is necessary. Couldn't clients
instead call `LookupFieldOrMethod` on the pointer type `*T`
if the receiver is a `T` variable? The answer is that if
`T` is an interface type, the type `*T` has no methods at
all.)
The final two parameters of `LookupFieldOrMethod` are `(pkg
*Package, name string)`.
Together they specify the name of the field or method to look up.
This brings us to `Id`s.
# Ids
`LookupFieldOrMethod`'s need for a `Package` parameter
is a subtle consequence of the
[_Uniqueness of identifiers_](https://golang.org/ref/spec#Uniqueness_of_identifiers)
section in the Go spec: "Two
identifiers are different if they are spelled differently, or if they
appear in different packages and are not exported."
In practical terms, this means that a type may have two methods
(or two fields, or one of each) both named `f` so long as those
methods are defined in different packages, as in this example:
package a
type A int
func (A) f()
package b
type B int
func (B) f()
package c
import ( "a"; "b" )
type C struct{a.A; b.B} // C has two methods called f
The type `c.C` has two methods named `f`, but there is
no ambiguity because the two `f`s are distinct
identifiers---think of them as `fᵃ` and `fᵇ`.
For an exported method, this situation _would_ be ambiguous
because there is no distinction between `Fᵃ` and `Fᵇ`; there
is only `F`.
Despite having two methods called `f`, neither of them can be
called from within package `c` because `c` has no way to
identify them.
Within `c`, `f` is the identifier `fᶜ`, and
type `C` has no method of that name.
But if we pass an instance of `C` to code in package `a`
and call its `f` method via an interface, `fᵃ` is called.
The practical consequence for tool builders is that any time you need
to look up a field or method by name, or construct a map of fields and/or
methods keyed by name, it is not sufficient to use the object's name
as a key.
Instead, you must call the `Object.Id` method, which returns
a string that incorporates the object name, and for unexported
objects, the package path too.
There is also a standalone function `Id` that combines a name and
the package path in the same way:
func Id(pkg *Package, name string) string
This distinction applies to selections _`expr`_`.f`, but not
to lexical references `x` because for unexported identifiers,
declarations and references always appear in the same package.
Fun fact: the `reflect.StructField` type records both the
`Name` and the `PkgPath` strings for the same reason.
The `FieldByName` methods of `reflect.Value` and
`reflect.Type` match field names without regard to the package.
If there is more than one match, they return an invalid value.
# Method Sets
The _method set_ of a type is the set of methods that can be
called on any value of that type.
(A variable of type `T` has access to all the methods of type
`*T` as well, due to the implicit address-of operation during
method calls, but those extra methods are not part of the method set
of `T`.)
Clients can request the method set of a type `T` by calling
`NewMethodSet(T)`:
type MethodSet struct{ ... }
func NewMethodSet(T Type) *MethodSet
func (s *MethodSet) Len() int
func (s *MethodSet) At(i int) *Selection
func (s *MethodSet) Lookup(pkg *Package, name string) *Selection
The `Len` and `At` methods access a list of
`Selections`, all of kind `MethodVal`, ordered by `Id`.
The `Lookup` function allows lookup of a single method by
name (and package path, as explained in the previous section).
`NewMethodSet` can be expensive, so for applications that compute
method sets repeatedly, `golang.org/x/tools/go/types/typeutil`
provides a `MethodSetCache` type that records previous results.
If you only need a single method, don't construct the
`MethodSet` at all; it's cheaper to use
`LookupFieldOrMethod`.
The next program generates a boilerplate
declaration of a new concrete type that satisfies an existing
interface.
Here's an example:
```
$ ./skeleton io ReadWriteCloser buffer
// *buffer implements io.ReadWriteCloser.
type buffer struct{}
func (b *buffer) Close() error {
panic("unimplemented")
}
func (b *buffer) Read(p []byte) (n int, err error) {
panic("unimplemented")
}
func (b *buffer) Write(p []byte) (n int, err error) {
panic("unimplemented")
}
```
The three arguments are the package and the name of the existing
interface type, and the name of the new concrete type.
The `main` function (not shown) loads the specified package and
calls `PrintSkeleton` with the remaining two arguments:
// go get golang.org/x/example/gotypes/skeleton
```
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {
obj := pkg.Scope().Lookup(ifacename)
if obj == nil {
return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename)
}
if _, ok := obj.(*types.TypeName); !ok {
return fmt.Errorf("%v is not a named type", obj)
}
iface, ok := obj.Type().Underlying().(*types.Interface)
if !ok {
return fmt.Errorf("type %v is a %T, not an interface",
obj, obj.Type().Underlying())
}
// Use first letter of type name as receiver parameter.
if !isValidIdentifier(concname) {
return fmt.Errorf("invalid concrete type name: %q", concname)
}
r, _ := utf8.DecodeRuneInString(concname)
fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename)
fmt.Printf("type %s struct{}\n", concname)
mset := types.NewMethodSet(iface)
for i := 0; i < mset.Len(); i++ {
meth := mset.At(i).Obj()
sig := types.TypeString(meth.Type(), (*types.Package).Name)
fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n",
r, concname, meth.Name(),
strings.TrimPrefix(sig, "func"))
}
return nil
}
```
First, `PrintSkeleton` locates the package-level named interface
type, handling various error cases.
Then it chooses the name for the receiver of the new methods: the
first letter of the concrete type.
Finally, it iterates over the method set of the interface, printing
the corresponding concrete method declarations.
There's a subtlety in the declaration of `sig`, which is the
string form of the method signature.
We could have obtained this string from `meth.Type().String()`,
but this would cause any named types within it to be formatted with
the complete package path, for instance
`net/http.ResponseWriter`, which is informative in diagnostics
but not legal Go syntax.
The `TypeString` function (explained in [Formatting Values](#formatting-values)) allows the
caller to control how packages are printed.
Passing `(*types.Package).Name` causes only the package name
`http` to be printed, not the complete path.
Here's another example that illustrates it:
```
$ ./skeleton net/http Handler myHandler
// *myHandler implements net/http.Handler.
type myHandler struct{}
func (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) {
panic("unimplemented")
}
```
The following program inspects all pairs of package-level named types
in `pkg`, and reports the types that satisfy each interface type.
// go get golang.org/x/example/gotypes/implements
```
// Find all named types at package level.
var allNamed []*types.Named
for _, name := range pkg.Scope().Names() {
if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {
allNamed = append(allNamed, obj.Type().(*types.Named))
}
}
// Test assignability of all distinct pairs of
// named types (T, U) where U is an interface.
for _, T := range allNamed {
for _, U := range allNamed {
if T == U || !types.IsInterface(U) {
continue
}
if types.AssignableTo(T, U) {
fmt.Printf("%s satisfies %s\n", T, U)
} else if !types.IsInterface(T) &&
types.AssignableTo(types.NewPointer(T), U) {
fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U)
}
}
}
```
Given this input,
// go get golang.org/x/example/gotypes/implements
```
const input = `package main
type A struct{}
func (*A) f()
type B int
func (B) f()
func (*B) g()
type I interface { f() }
type J interface { g() }
`
```
the program prints:
```
$ go build golang.org/x/example/gotypes/implements
$ ./implements
*hello.A satisfies hello.I
hello.B satisfies hello.I
*hello.B satisfies hello.J
```
Notice that the method set of `B` does not include `g`, but
the method set of `*B` does.
That's why we needed the second assignability check, using the pointer
type `types.NewPointer(T)`.
# Constants
A constant expression is one whose value is guaranteed to be computed at
compile time.
Constant expressions may appear in types, specifically as the length
of an array type such as `[16]byte`, so one of the jobs of the
type checker is to compute the value of each constant expression.
As we saw in the `typeandvalue` example, the type checker records
the value of each constant expression like `"Hello, " + "world"`,
storing it in the `Value` field of the `TypeAndValue` struct.
Constants are represented using the `Value` interface from the
`go/constant` package.
package constant // go/constant
type Value interface {
Kind() Kind
}
type Kind int // one of Unknown, Bool, String, Int, Float, Complex
The interface has only one method, for discriminating the various
kinds of constants, but the package provides many functions for
inspecting a value of a known kind,
// Accessors
func BoolVal(x Value) bool
func Float32Val(x Value) (float32, bool)
func Float64Val(x Value) (float64, bool)
func Int64Val(x Value) (int64, bool)
func StringVal(x Value) string
func Uint64Val(x Value) (uint64, bool)
func Bytes(x Value) []byte
func BitLen(x Value) int
func Sign(x Value) int
for performing arithmetic on values,
// Operations
func Compare(x Value, op token.Token, y Value) bool
func UnaryOp(op token.Token, y Value, prec uint) Value
func BinaryOp(x Value, op token.Token, y Value) Value
func Shift(x Value, op token.Token, s uint) Value
func Denom(x Value) Value
func Num(x Value) Value
func Real(x Value) Value
func Imag(x Value) Value
and for constructing new values:
// Constructors
func MakeBool(b bool) Value
func MakeFloat64(x float64) Value
func MakeFromBytes(bytes []byte) Value
func MakeFromLiteral(lit string, tok token.Token, prec uint) Value
func MakeImag(x Value) Value
func MakeInt64(x int64) Value
func MakeString(s string) Value
func MakeUint64(x uint64) Value
func MakeUnknown() Value
All numeric `Value`s, whether integer or floating-point, signed or
unsigned, or real or complex, are represented more precisely than
ordinary Go types like `int64` and `float64`.
Internally, the `go/constant` package uses multi-precision data types
like `Int`, `Rat`, and `Float` from the `math/big` package so that
`Values` and their arithmetic operations are accurate to at least 256
bits, as required by the Go specification.
<!-- TODO example -->
# Size and Alignment
Because the calls `unsafe.Sizeof(v)`, `unsafe.Alignof(v)`,
and `unsafe.Offsetof(v.f)` are all constant expressions, the type
checker must be able to compute the memory layout of any value
`v`.
By default, the type checker uses the same layout algorithm as the Go
1.5 `gc` compiler targeting `amd64`.
Clients can configure the type checker to use a different algorithm by
providing an instance of the `types.Sizes` interface in the
`types.Config` struct:
package types
type Sizes interface {
Alignof(T Type) int64
Offsetsof(fields []*Var) []int64
Sizeof(T Type) int64
}
For common changes, like reducing the word size to 32 bits, clients
can use an instance of `StdSizes`:
type StdSizes struct {
WordSize int64
MaxAlign int64
}
This type has two basic size and alignment parameters from which it
derives all the other values using common assumptions.
For example, pointers, functions, maps, and channels fit in one word,
strings and interfaces require two words, and slices need three.
The default behaviour is equivalent to `StdSizes{8, 8}`.
For more esoteric layout changes, you'll need to write a new
implementation of the `Sizes` interface.
The `hugeparam` program below prints all function parameters and
results whose size exceeds a threshold.
By default, the threshold is 48 bytes, but you can set it via the
`-bytes` command-line flag.
Such a tool could help identify inefficient parameter passing in your
programs.
// go get golang.org/x/example/gotypes/hugeparam
```
var bytesFlag = flag.Int("bytes", 48, "maximum parameter size in bytes")
func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {
checkTuple := func(descr string, tuple *types.Tuple) {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {
fmt.Printf("%s: %q %s: %s = %d bytes\n",
fset.Position(v.Pos()),
v.Name(), descr, v.Type(), sz)
}
}
}
checkSig := func(sig *types.Signature) {
checkTuple("parameter", sig.Params())
checkTuple("result", sig.Results())
}
for _, file := range files {
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.FuncDecl:
checkSig(info.Defs[n.Name].Type().(*types.Signature))
case *ast.FuncLit:
checkSig(info.Types[n.Type].Type.(*types.Signature))
}
return true
})
}
}
```
As before, `Inspect` applies a function to every node in the AST.
The function cares about two kinds of nodes: declarations of named
functions and methods (`*ast.FuncDecl`) and function literals
(`*ast.FuncLit`).
Observe the two cases' different logic to obtain the type of each
function.
Here's a typical invocation on the standard `encoding/xml` package.
It reports a number of places where the 7-word
[`StartElement` type](https://pkg.go.dev/encoding/xml#StartElement)
is copied.
```
% ./hugeparam encoding/xml
/go/src/encoding/xml/marshal.go:167:50: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:734:97: "" result: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:761:51: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:781:68: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/xml.go:72:30: "" result: encoding/xml.StartElement = 56 bytes
```
# Imports
The type checker's `Check` function processes a slice of parsed
files (`[]*ast.File`) that make up one package.
When the type checker encounters an import declaration, it needs the
type information for the objects in the imported package.
It gets it by calling the `Import` method of the `Importer`
interface shown below, an instance of which must be provided by the
`Config`.
This separation of concerns relieves the type checker from having to
know any of the details of Go workspace organization, `GOPATH`,
compiler file formats, and so on.
type Importer interface {
Import(path string) (*Package, error)
}
Most of our examples used the simplest `Importer` implementation,
`importer.Default()`, provided by the `go/importer` package.
This importer looks in `$GOROOT` and `$GOPATH` for `.a`
files written by the compiler (`gc` or `gccgo`)
that was used to build the program.
In addition to object code, these files contain _export data_,
that is, a description of all the objects declared by the package, and
also of any objects from other packages that were referred to indirectly.
Because export data includes information about dependencies, the type
checker need load at most one file per import, instead of one per
transitive dependency.
Compiler export data is compact and efficient to locate, load, and
parse, but it has several shortcomings.
First, it does not contain position information for imported
objects, reducing the quality of certain diagnostic messages.
Second, it does not contain complete syntax trees nor semantic information
about the contents of function bodies, so it is not suitable for
interprocedural analyses.
Third, compiler object data may be stale. Nothing detects or ensures
that the object files are more recent than the source files from which
they were derived.
Generally, object data for standard packages is likely to be
up-to-date, but for user packages, it depends on how recently the user
ran a `go install` or `go build -i` command.
The [`golang.org/tools/x/go/packages`
package](https://pkg.go.dev/golang.org/x/tools/go/packages) provides
a comprehensive means of loading packages from source.
It runs `go list` to query the project metadata,
performs [`cgo`](https://golang.org/cmd/cgo/cgo) preprocessing if necessary,
reads and parses the source files,
and optionally type-checks each package.
It can load a whole program from source, or load just the initial
packages from source and load all their dependencies from export data.
It loads independent packages in parallel to hide I/O latency, and
detects and reports import cycles.
For each package, it provides the `types.Package` containing the
package's lexical environment, the list of `ast.File` syntax
trees for each file in the package, the `types.Info` containing
type information for each syntax node, a list of type errors
associated with that package, and other information too.
Since some of this information is more costly to compute,
the API allows you to select which parts you need,
but since this is a tutorial we'll generally request complete
information so that it is easier to explore.
The `doc` program below demonstrates a simple use of `go/packages`.
It is a rudimentary implementation of `go doc` that prints the type,
methods, and documentation of the package-level object specified on
the command line.
Here's an example:
```
$ ./doc net/http File
type net/http.File interface{Readdir(count int) ([]os.FileInfo, error); Seek(offset int64, whence int) (int64, error); Stat() (os.FileInfo, error); io.Closer; io.Reader}
$GOROOT/src/io/io.go:92:2: method (net/http.File) Close() error
$GOROOT/src/io/io.go:71:2: method (net/http.File) Read(p []byte) (n int, err error)
/go/src/net/http/fs.go:65:2: method (net/http.File) Readdir(count int) ([]os.FileInfo, error)
$GOROOT/src/net/http/fs.go:66:2: method (net/http.File) Seek(offset int64, whence int) (int64, error)
/go/src/net/http/fs.go:67:2: method (net/http.File) Stat() (os.FileInfo, error)
A File is returned by a FileSystem's Open method and can be
served by the FileServer implementation.
The methods should behave the same as those on an *os.File.
```
Observe that it prints the correct location of each method
declaration, even though, due to embedding, some of
`http.File`'s methods were declared in another package.
Here's the first part of the program, showing how to load
complete type information including typed syntax,
for a single package `pkgpath`,
plus exported type information for its dependencies.
// go get golang.org/x/example/gotypes/doc
```
pkgpath, name := os.Args[1], os.Args[2]
// Load complete type information for the specified packages,
// along with type-annotated syntax.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
// Find the package and package-level object.
pkg := pkgs[0]
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
log.Fatalf("%s.%s not found", pkg.Types.Path(), name)
}
```
By default, `go/packages`, instructs the parser to retain comments during parsing.
The rest of the program prints the output:
// go get golang.org/x/example/gotypes/doc
```
// Print the object and its methods (incl. location of definition).
fmt.Println(obj)
for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel)
}
// Find the path from the root of the AST to the object's position.
// Walk up to the enclosing ast.Decl for the doc comment.
for _, file := range pkg.Syntax {
pos := obj.Pos()
if !(file.FileStart <= pos && pos < file.FileEnd) {
continue // not in this file
}
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
fmt.Println("\n", n.Doc.Text())
return
case *ast.FuncDecl:
fmt.Println("\n", n.Doc.Text())
return
}
}
}
```
We used `IntuitiveMethodSet` to compute the method set, instead
of `NewMethodSet`.
The result of this convenience function, which is intended for use in
user interfaces, includes methods of `*T` as well as those of
`T`, since that matches most users' intuition about the method
set of a type.
(Our example, `http.File`, didn't illustrate the difference, but try
running it on a type with both value and pointer methods.)
Also notice `PathEnclosingInterval`, which finds the set of AST
nodes that enclose a particular point, in this case, the object's
declaring identifier.
By walking up with path, we find the enclosing declaration, to which
the documentation is attached.
# Formatting support
All types that satisfy `Type` or `Object` define a
`String` method that formats the type or object in a readable
notation. `Selection` also provides a `String` method.
All package-level objects within these data structures are
printed with the complete package path, as in these examples:
[]encoding/json.Marshaler // a *Slice type
encoding/json.Marshal // a *Func object
(*encoding/json.Encoder).Encode // a *Func object (method)
func (enc *encoding/json.Encoder) Encode(v interface{}) error // a method *Signature
func NewEncoder(w io.Writer) *encoding/json.Encoder // a function *Signature
This notation is unambiguous, but it is not legal Go syntax.
Also, package paths may be long, and the same package path may appear
many times in a single string, for instance, when formatting a
function of several parameters.
Because these strings often form part of a tool's user interface---as
with the diagnostic messages of `hugeparam` or the code generated
by `skeleton`---many clients want more control over the
formatting of package names.
The `go/types` package provides these alternatives to the
`String` methods:
func ObjectString(obj Object, qf Qualifier) string
func TypeString(typ Type, qf Qualifier) string
func SelectionString(s *Selection, qf Qualifier) string
type Qualifier func(*Package) string
The `TypeString`, `ObjectString`, and `SelectionString`
functions are like the `String` methods of the respective types,
but they accept an additional argument, a `Qualifier`.
A `Qualifier` is a client-provided function that determines how a
package name is rendered as a string.
If it is nil, the default behavior is to print the package's
path, just like the `String` methods do.
If a caller passes `(*Package).Name` as the qualifier, that is, a
function that accepts a package and returns its `Name`, then
objects are qualified only by the package name.
The above examples would look like this:
[]json.Marshaler
json.Marshal
(*json.Encoder).Encode
func (enc *json.Encoder) Encode(v interface{}) error
func NewEncoder(w io.Writer) *json.Encoder
Often when a tool prints some output, it is implicitly in the
context of a particular package, perhaps one specified by the
command line or HTTP request.
In that case, it is more natural to omit the package qualification
altogether for objects belonging to that package, but to qualify all
other objects by their package's path.
That's what the `RelativeTo(pkg)` qualifier does:
func RelativeTo(pkg *Package) Qualifier
The examples below show how `json.NewEncoder` would be printed
using three qualifiers, each relative to a different package:
// RelativeTo "encoding/json":
func NewEncoder(w io.Writer) *Encoder
// RelativeTo "io":
func NewEncoder(w Writer) *encoding/json.Encoder
// RelativeTo any other package:
func NewEncoder(w io.Writer) *encoding/json.Encoder
Another qualifier that may be relevant to refactoring tools (but is
not currently provided by the type checker) is one that renders each
package name using the locally appropriate name within a given source
file.
Its behavior would depend on the set of import declarations, including
renaming imports, within that source file.
# Getting from A to B
The type checker and its related packages represent many aspects of a
Go program in many different ways, and analysis tools must often map
between them.
For instance, a named entity may be identified by its `Object`;
by its declaring identifier (`ast.Ident`) or by any referring
identifier; by its declaring `ast.Node`; by the position
(`token.Pos`) of any those nodes; or by the filename and
line/column number (or byte offset) of those `token.Pos` values.
In this section, we'll list solutions to a number of common problems
of the form "I have an A; I need the corresponding B".
To map **from a `token.Pos` to an `ast.Node`**, call the
helper function
[`astutil.PathEnclosingInterval`](https://pkg.go.dev/golang.org/x/tools/go/ast/astutil#PathEnclosingInterval).
It returns the enclosing `ast.Node`, and all its ancestors up to
the root of the file.
If you don't know which file `*ast.File` the `token.Pos` belongs to,
you can iterate over the parsed files of the package and quickly test
whether its position falls within the file's range,
from `File.FileStart` to `File.FileEnd`.
To map **from an `Object` to its declaring syntax**, call
`Pos` to get its position, then use `PathEnclosingInterval` as before.
This approach is suitable for a one-off query. For repeated use, it
may be more efficient to visit the syntax tree and construct the
mapping between declarations and objects.
To map **from an `ast.Ident` to the `Object`** it refers to (or
declares), consult the `Uses` or `Defs` map for the
package, as shown in [Identifier Resolution](#identifier-resolution).
To map **from an `Object` to its documentation**, find the
object's declaration, and look at the attached `Doc` field.
You must have set the parser's `ParseComments` flag.
See the `doc` example in [Imports](#imports).
|
gotypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/go-types.md
|
# `go/types`: The Go Type Checker
This document is maintained by Alan Donovan `adonovan@google.com`.
[October 2015 GothamGo talk on go/types](https://docs.google.com/presentation/d/13OvHYozAUBeISPRoLgG7kMBuja1NsU1D_mMlmbaYojk/view)
# Contents
%toc
# Changes in Go 1.18
Go 1.18 introduces generics, and several corresponding new APIs for `go/types`.
This document is not yet up-to-date for these changes, but a guide to the new
changes exists at
[`x/exp/typeparams/example`](https://github.com/golang/exp/tree/master/typeparams/example).
# Introduction
The [`go/types` package]('https://golang.org/pkg/go/types) is a
type-checker for Go programs, designed by Robert Griesemer.
It became part of Go's standard library in Go 1.5.
Measured by lines of code and by API surface area, it is one of the
most complex packages in Go's standard library, and using it requires
a firm grasp of the structure of Go programs.
This tutorial will help you find your bearings.
It comes with several example programs that you can obtain with `go get` and play with.
We assume you are a proficient Go programmer who wants to build tools
to analyze or manipulate Go programs and that you have some knowledge
of how a typical compiler works.
The type checker complements several existing
standard packages for analyzing Go programs.
We've listed them below.
→ go/types
go/constant
go/parser
go/ast
go/scanner
go/token
Starting at the bottom, the
[`go/token` package](http://golang.org/pkg/go/token)
defines the lexical tokens of Go.
The [`go/scanner` package](http://golang.org/pkg/go/scanner) tokenizes an input stream and records
file position information for use in diagnostics
or for file surgery in a refactoring tool.
The [`go/ast` package](http://golang.org/pkg/go/ast)
defines the data types of the abstract syntax tree (AST).
The [`go/parser` package](http://golang.org/pkg/go/parser)
provides a robust recursive-descent parser that constructs the AST.
And [`go/constant`](http://golang.org/pkg/go/constant)
provides representations and arithmetic operations for the values of compile-time
constant expressions, as we'll see in
[Constants](#constants).
The [`golang.org/x/tools/go/packages` package](https://pkg.go.dev/golang.org/x/tools/go/packages)
from the `x/tools` repository is a client of the type
checker that loads, parses, and type-checks a complete Go program from
source code.
We use it in some of our examples and you may find it useful too.
The Go type checker does three main things.
First, for every name in the program, it determines which declaration
the name refers to; this is known as _identifier resolution_.
Second, for every expression in the program, it determines what type
that expression has, or reports an error if the expression has no
type, or has an inappropriate type for its context; this is known as
_type deduction_.
Third, for every constant expression in the program, it determines the
value of that constant; this is known as _constant evaluation_.
Superficially, it appears that these three processes could be done
sequentially, in the order above, but perhaps surprisingly, they must
be done together.
For example, the value of a constant may depend on the type of an
expression due to operators like `unsafe.Sizeof`.
Conversely, the type of an expression may depend on the value of a
constant, since array types contain constants.
As a result, type deduction and constant evaluation must be done
together.
As another example, we cannot resolve the identifier `k` in the composite
literal `T{k: 0}` until we know whether `T` is a struct type.
If it is, then `k` must be found among `T`'s fields.
If not, then `k` is an ordinary reference
to a constant or variable in the lexical environment.
Consequently, identifier resolution and type deduction are also
inseparable in the general case.
Nonetheless, the three processes of identifier resolution, type
deduction, and constant evaluation can be separated for the purpose of
explanation.
# An Example
The code below shows the most basic use of the type checker to check
the _hello, world_ program, supplied as a string.
Later examples will be variations on this one, and we'll often omit
boilerplate details such as parsing.
To check out and build the examples,
run `go get golang.org/x/example/gotypes/...`.
%include pkginfo/main.go
First, the program creates a
[`token.FileSet`](http://golang.org/pkg/go/token/#FileSet).
To avoid the need to store file names and line and column
numbers in every node of the syntax tree, the `go/token` package
provides `FileSet`, a data structure that stores this information
compactly for a sequence of files.
A `FileSet` records each file name only once, and records
only the byte offsets of each newline, allowing a position within
any file to be identified using a small integer called a
`token.Pos`.
Many tools create a single `FileSet` at startup.
Any part of the program that needs to convert a `token.Pos` into
an intelligible location---as part of an error message, for
instance---must have access to the `FileSet`.
Second, the program parses the input string.
More realistic packages contain several source files, so the parsing
step must be repeated for each one, or better, done in parallel.
Third, it creates a `Config` that specifies type-checking options.
Since the _hello, world_ program uses imports, we must indicate
how to locate the imported packages.
Here we use `importer.Default()`, which loads compiler-generated
export data, but we'll explore alternatives in [Imports](#imports).
Fourth, the program calls `Check`.
This creates a `Package` whose path is `"cmd/hello"`, and
type-checks each of the specified files---just one in this example.
The final (nil) argument is a pointer to an optional `Info`
struct that returns additional deductions from the type checker; more
on that later.
`Check` returns a `Package` even when it also returns an error.
The type checker is robust to ill-formed input,
and goes to great lengths to report accurate
partial information even in the vicinity of syntax or type errors.
`Package` has this definition:
type Package struct{ ... }
func (*Package) Path() string
func (*Package) Name() string
func (*Package) Scope() *Scope
func (*Package) Imports() []*Package
Finally, the program prints the attributes of the package, shown below.
(The hexadecimal number may vary from one run to the next.)
%include pkginfo/main.go output -
A package's `Path`, such as `"encoding/json"`, is the string
by which import declarations identify it.
It is unique within a `$GOPATH` workspace,
and for published packages it must be globally unique.
A package's `Name` is the identifier in the `package`
declaration of each source file within the package, such as `json`.
The type checker reports an error if not all the package declarations in
the package agree.
The package name determines how the package is known when it is
imported into a file (unless a renaming import is used),
but is otherwise not visible to a program.
`Scope` returns the package's [_lexical block_](#scopes),
which provides access to all the named entities or
[_objects_](#objects) declared at package level.
`Imports` returns the set of packages directly imported by this
one, and may be useful for computing dependencies
([Initialization Order](#initialization-order)).
# Objects
The task of identifier resolution is to map every identifier in the
syntax tree, that is, every `ast.Ident`, to an object.
For our purposes, an _object_ is a named entity created by a
declaration, such as a `var`, `type`, or `func`
declaration.
(This is different from the everyday meaning of object in
object-oriented programming.)
Objects are represented by the `Object` interface:
type Object interface {
Name() string // package-local object name
Exported() bool // reports whether the name starts with a capital letter
Type() Type // object type
Pos() token.Pos // position of object identifier in declaration
Parent() *Scope // scope in which this object is declared
Pkg() *Package // nil for objects in the Universe scope and labels
Id() string // object id (see Ids section below)
}
The first four methods are straightforward; we'll explain the other
three later.
`Name` returns the object's name---an identifier.
`Exported` is a convenience method that reports whether the first
letter of `Name` is a capital, indicating that the object may be
visible from outside the package.
It's a shorthand for `ast.IsExported(obj.Name())`.
`Type` returns the object's type; we'll come back to that in
[Types](#types).
`Pos` returns the source position of the object's declaring identifier.
To make sense of a `token.Pos`, we need to call the
`(*token.FileSet).Position` method, which returns a struct with
individual fields for the file name, line number, column, and byte
offset, though usually we just call its `String` method:
fmt.Println(fset.Position(obj.Pos())) // "hello.go:10:6"
Not all objects carry position information.
Since the file format for compiler export data ([Imports](#imports))
does not record position information, calling `Pos` on an object
imported from such a file returns zero, also known as
`token.NoPos`.
There are eight kinds of objects in the Go type checker.
Most familiar are the kinds that can be declared at package level:
constants, variables, functions, and types.
Less familiar are statement labels, imported package names
(such as `json` in a file containing an `import "encoding/json"`
declaration), built-in functions (such as `append` and
`len`), and the pre-declared `nil`.
The eight types shown below are the only concrete types that satisfy
the `Object` interface.
In other words, `Object` is a _discriminated union_ of 8
possible types, and we commonly use a type switch to distinguish them.
Object = *Func // function, concrete method, or abstract method
| *Var // variable, parameter, result, or struct field
| *Const // constant
| *TypeName // type name
| *Label // statement label
| *PkgName // package name, e.g. json after import "encoding/json"
| *Builtin // predeclared function such as append or len
| *Nil // predeclared nil
`Object`s are canonical.
That is, two `Object`s `x` and `y` denote the same
entity if and only if `x==y`.
Object identity is significant, and objects are routinely compared by
the addresses of the underlying pointers.
Although a package-level object is uniquely identified by its name
and enclosing package, for other objects there is no simple way to
obtain a string that uniquely identifies it.
The `Parent` method returns the `Scope` (lexical block) in
which the object was declared; we'll come back to this in
[Scopes](#scopes).
Fields and methods are not found in the lexical environment, so
their objects have no `Parent`.
<!-- TODO check this -->
The `Pkg` method returns the `Package` to which this object
belongs, even for objects not declared at package level.
Only predeclared objects have no package.
The `Id` method will be explained in [Ids](#ids).
Not all methods make sense for each kind of object. For instance,
the last four kinds above have no meaningful `Type` method.
And some kinds of objects have methods in addition to those required by the
`Object` interface:
func (*Func) Scope() *Scope
func (*Var) Anonymous() bool
func (*Var) IsField() bool
func (*Const) Val() constant.Value
func (*TypeName) IsAlias() bool
func (*PkgName) Imported() *Package
`(*Func).Scope` returns the [lexical block](#scopes)
containing the function's parameters, results,
and other local declarations.
`(*Var).IsField` distinguishes struct fields from ordinary
variables, and `(*Var).Anonymous` discriminates named fields like
the one in `struct{T T}` from anonymous fields like the one in `struct{T}`.
`(*Const).Val` returns the value of a named [constant](#constants).
`(*TypeName).IsAlias`, introduced in Go 1.9, reports whether the
type name is simply an alias for a type (as in `type I = int`),
as opposed to a definition of a [`Named`](#named-types) type, as
in `type Celsius float64`.
`(*PkgName).Imported` returns the package (for instance,
`encoding/json`) denoted by a given import name such as `json`.
Each time a package is imported, a new `PkgName` object is
created, usually with the same name as the `Package` it
denotes, but not always, as in the case of a renaming import.
`PkgName`s are objects, but `Package`s are not.
We'll look more closely at this in [Imports](#imports).
All relationships between the syntax trees (`ast.Node`s) and type
checker data structures such as `Object`s and `Type`s are
stored in mappings outside the syntax tree itself.
Be aware that the `go/ast` package also defines a type called
`Object` that resembles---and predates---the type checker's
`Object`, and that `ast.Object`s are held directly by
identifiers in the AST.
They are created by the parser, which has a necessarily limited view
of the package, so the information they represent is at best partial and
in some cases wrong, as in the `T{k: 0}` example mentioned above.
If you are using the type checker, there is no reason to use the older
`ast.Object` mechanism.
# Identifier Resolution
Identifier resolution computes the relationship between
identifiers and objects.
Its results are recorded in the `Info` struct optionally passed
to `Check`.
The fields related to identifier resolution are shown below.
type Info struct {
Defs map[*ast.Ident]Object
Uses map[*ast.Ident]Object
Implicits map[ast.Node]Object
Selections map[*ast.SelectorExpr]*Selection
Scopes map[ast.Node]*Scope
...
}
Since not all facts computed by the type checker are needed by every
client, the API lets clients control which components of the result
should be recorded and which discarded: only fields that hold a
non-nil map will be populated during the call to `Check`.
The two fields of type `map[*ast.Ident]Object` are the most important:
`Defs` records _declaring_ identifiers and
`Uses` records _referring_ identifiers.
In the example below, the comments indicate which identifiers are of
which kind.
var x int // def of x, use of int
fmt.Println(x) // uses of fmt, Println, and x
type T struct{U} // def of T, use of U (type), def of U (field)
The final line above illustrates why we don't combine `Defs` and
`Uses` into one map.
In the anonymous field declaration `struct{U}`, the
identifier `U` is both a use of the type `U` (a
`TypeName`) and a definition of the anonymous field (a
`Var`).
The function below prints the location of each referring and defining
identifier in the input program, and the object it refers to.
%include defsuses/main.go
Let's use the _hello, world_ program again as the input:
%include hello/hello.go
This is what it prints:
%include defsuses/main.go output -
Notice that the `Defs` mapping may contain nil entries in a few
cases.
The first line of output reports that the package identifier
`main` is present in the `Defs` mapping, but has no
associated object.
The `Implicits` mapping handles two cases of the syntax in
which an `Object` is declared without an `ast.Ident`, namely type
switches and import declarations.
<!--
A third case: an anonymous function parameter or result variable.
These objects are returned by Signature.Param and Signature.Result.
-->
In the type switch below, which declares a local variable `y`,
the type of `y` is different in each case of the switch:
switch y := x.(type) {
case int:
fmt.Printf("%d", y)
case string:
fmt.Printf("%q", y)
default:
fmt.Print(y)
}
To represent this, for each single-type case, the type checker creates
a separate `Var` object for `y` with the appropriate type,
and `Implicits` maps each `ast.CaseClause` to the `Var`
for that case.
The `default` case, the `nil` case, and cases with more than one
type all use the regular `Var` object that is associated with the
identifier `y`, which is found in the `Defs` mapping.
The import declaration below defines the name `json` without an
`ast.Ident`:
import "encoding/json"
`Implicits` maps this `ast.ImportSpec` to the `PkgName`
object named `json` that it implicitly declares.
The `Selections` mapping, of type
`map[*ast.SelectorExpr]*Selection`, records the meaning of each
expression of the form _`expr`_`.f`, where _`expr`_ is
an expression or type and `f` is the name of a field or method.
These expressions, called _selections_, are represented by
`ast.SelectorExpr` nodes in the AST.
We'll talk more about the `Selection` type in [Selections](#selections).
Not all `ast.SelectorExpr` nodes represent selections.
Expressions like `fmt.Println`, in which a package name precedes
the dot, are _qualified identifiers_.
They do not appear in the `Selections` mapping, but their
constituent identifiers (such as `fmt` and `Println`) both
appear in `Uses`.
Referring identifiers that are not part of an `ast.SelectorExpr`
are _lexical references_.
That is, they are resolved to an object by searching for the
innermost enclosing lexical declaration of that name.
We'll see how that search works in the next section.
# Scopes
The `Scope` type is a mapping from names to objects.
type Scope struct{ ... }
func (s *Scope) Names() []string
func (s *Scope) Lookup(name string) Object
`Names` returns the set of names in the mapping, in sorted order.
(It is not a simple accessor though, so call it sparingly.)
The `Lookup ` method returns the object for a given name, so we
can print all the entries or _bindings_ in a scope like this:
for _, name := range scope.Names() {
fmt.Println(scope.Lookup(name))
}
The _scope_ of a declaration of a name is the region of
program source in which a reference to the name resolves to that
declaration. That is, scope is a property of a declaration.
However, in the `go/types` API, the `Scope` type represents
a _lexical block_, which is one component of the lexical
environment.
Consider the _hello, world_ program again:
package main
import "fmt"
func main() {
const message = "hello, world"
fmt.Println(message)
}
There are four lexical blocks in this program.
The outermost one is the _universe block_, which maps the
pre-declared names like `int`, `true`, and `append` to
their objects---a `TypeName`, a `Const`, and a
`Builtin`, respectively.
The universe block is represented by the global variable
`Universe`, of type `*Scope`, although it's logically a
constant so you shouldn't modify it.
Next is the _package block_, which maps `"main"` to the
`main` function.
Following that is the _file block_, which maps `"fmt"` to
the `PkgName` object for this import of the `fmt` package.
And finally, the innermost block is that of function `main`, a
local block, which contains the declaration of `message`, a `Const`.
The `main` function is trivial, but many functions contain
several blocks since each `if`, `for`, `switch`,
`case`, or `select` statement creates at least one
additional block.
Local blocks nest to arbitrary depths.
The structure of the lexical environment thus forms a tree, with the
universe block at the root, the package blocks beneath it, the file
blocks beneath them, and then any number of local blocks beneath the
files.
We can access and navigate this tree structure with the following
methods of `Scope`:
func (s *Scope) Parent() *Scope
func (s *Scope) NumChildren() int
func (s *Scope) Child(i int) *Scope
`Parent` lets us walk up the tree, and `Child`
lets us walk down it.
Note that although the `Parent` of every package `Scope` is
`Universe`, `Universe` has no children.
This asymmetry is a consequence of using a global variable to hold
`Universe`.
To obtain the universe block, we use the `Universe` global variable.
To obtain the lexical block of a `Package`, we call its
`Scope` method.
To obtain the scope of a file (`*ast.File`), or any smaller piece
of syntax such as an `*ast.IfStmt`, we consult the `Scopes`
mapping in the `Info` struct, which maps each block-creating
syntax node to its block.
The lexical block of a named function or method can also be obtained
by calling its `(*Func).Scope` method.
<!--
TODO: explain explicit and implicit blocks
TODO: explain Dot imports.
TODO: explain that Func blocks are associated with FuncType (not FuncDecl or FuncLit)
-->
To look up a name in the lexical environment, we must search the tree
of lexical blocks, starting at a particular `Scope` and walking
up to the root until a declaration of the name is found.
For convenience, the `LookupParent` method does this, returning
not just the object, if found, but also the `Scope` in which it was
declared, which may be an ancestor of the initial one:
func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)
The `pos` parameter determines the position in the source code at
which the name should be resolved.
The effective lexical environment is different at each point in the
block because it depends on which local declarations appear
before or after that point.
(We'll see an illustration in a moment.)
`Scope` has several other methods relating to source positions:
func (s *Scope) Pos() token.Pos
func (s *Scope) End() token.Pos
func (s *Scope) Contains(pos token.Pos) bool
func (s *Scope) Innermost(pos token.Pos) *Scope
`Pos` and `End` report the `Scope`'s start and end
position which, for explicit blocks, coincide with its curly
braces.
`Contains` is a convenience method that reports whether a
position lies in this interval.
`Innermost` returns the innermost scope containing the specified
position, which may be a child or other descendent of the initial
scope.
These features are useful for tools that wish to resolve names or
evaluate constant expressions as if they had appeared at a particular
point within the program.
The next example program finds all the comments in the input,
treating the contents of each one as a name. It looks up each name in
the environment at the position of the comment, and prints what it
finds.
Observe that the `ParseComments` flag directs the parser to
preserve comments in the input.
%include lookup/lookup.go main
The expression `pkg.Scope().Innermost(pos)` finds the innermost
`Scope` that encloses the comment, and `LookupParent(name, pos)`
does a name lookup at a specific position in that lexical block.
A typical input is shown below.
The first comment causes a lookup of `"append"` in the file block.
The second comment looks up `"fmt"` in the `main` function's block,
and so on.
%include lookup/lookup.go input -
Here's the output:
%include lookup/lookup.go output -
Notice how the two lookups of `main` return different results,
even though they occur in the same block, because one precedes the
declaration of the local variable named `main` and the other
follows it.
Also notice that there are two lookups of the name `x` but only
the first one, in the function block, succeeds.
Download the program and modify both the input program and
the set of comments to get a better feel for how name resolution works.
The table below summarizes which kinds of objects may be declared at
each level of the tree of lexical blocks.
Universe File Package Local
Builtin ✔
Nil ✔
Const ✔ ✔ ✔
TypeName ✔ ✔ ✔
Func ✔
Var ✔ ✔
PkgName ✔
Label ✔
# Initialization Order
In the course of identifier resolution, the type checker constructs a
graph of references among declarations of package-level variables and
functions.
The type checker reports an error if the initializer expression for a
variable refers to that variable, whether directly or indirectly.
The reference graph determines the initialization order of the
package-level variables, as required by the Go spec, using a
breadth-first algorithm.
First, variables in the graph with no successors are removed, sorted
into the order in which they appear in the source code, then added
to a list. This creates more variables that have no successors.
The process repeats until they have all been removed.
The result is available in the `InitOrder` field of the
`Info` struct, whose type is `[]Initializer`.
type Info struct {
...
InitOrder []Initializer
...
}
type Initializer struct {
Lhs []*Var // var Lhs = Rhs
Rhs ast.Expr
}
Each element of the list represents a single initializer expression
that must be executed, and the variables to which it is assigned.
The variables may number zero, one, or more, as in these examples:
var _ io.Writer = new(bytes.Buffer)
var rx = regexp.MustCompile("^b(an)*a$")
var cwd, cwdErr = os.Getwd()
This process governs the initialization order of variables within a
package.
Across packages, dependencies must be initialized first, although the
order among them is not specified.
That is, any topological order of the import graph will do.
The `(*Package).Imports` method returns the set of direct
dependencies of a package.
# Types
The main job of the type checker is, of course, to deduce the type
of each expression and to report type errors.
Like `Object`, `Type` is an interface type used as a
discriminated union of several concrete types but, unlike
`Object`, `Type` has very few methods because types have
little in common with each other.
Here is the interface:
type Type interface {
Underlying() Type
}
And here are the eleven concrete types that satisfy it:
Type = *Basic
| *Pointer
| *Array
| *Slice
| *Map
| *Chan
| *Struct
| *Tuple
| *Signature
| *Named
| *Interface
With the exception of `Named` types, instances of `Type` are
not canonical.
That is, it is usually a mistake to compare types using `t1==t2`
since this equivalence is not the same as the
[type identity relation](https://golang.org/ref/spec#Type_identity)
defined by the Go spec.
Use this function instead:
func Identical(t1, t2 Type) bool
For the same reason, you should not use a `Type` as a key in a map.
The [`golang.org/x/tools/go/types/typeutil` package](https://pkg.go.dev/golang.org/x/tools/go/types/typeutil)
provides a map keyed by types that uses the correct
equivalence relation.
The Go spec defines three relations over types.
[_Assignability_](https://golang.org/ref/spec#Assignability)
governs which pairs of types may appear on the
left- and right-hand side of an assignment, including implicit
assignments such as function calls, map and channel operations, and so
on.
[_Comparability_](https://golang.org/ref/spec#Comparison_operators)
determines which types may appear in a comparison `x==y` or a
switch case or may be used as a map key.
[_Convertibility_](https://golang.org/ref/spec#Conversions)
governs which pairs of types are allowed in a conversion operation
`T(v)`.
You can query these relations with the following predicate functions:
func AssignableTo(V, T Type) bool
func Comparable(T Type) bool
func ConvertibleTo(V, T Type) bool
Let's take a look at each kind of type.
## Basic types
`Basic` represents all types that are not composed from simpler
types.
This is essentially the set of underlying types that a constant expression is
permitted to have--strings, booleans, and numbers---but it also
includes `unsafe.Pointer` and untyped nil.
type Basic struct{...}
func (*Basic) Kind() BasicKind
func (*Basic) Name() string
func (*Basic) Info() BasicInfo
The `Kind` method returns an "enum" value that indicates which
basic type this is.
The kinds `Bool`, `String`, `Int16`, and so on,
represent the corresponding predeclared boolean, string, or numeric
types.
There are two synonyms: `Byte` is equivalent to `Uint8`
and `Rune` is equivalent to `Int32`.
The kind `UnsafePointer` represents `unsafe.Pointer`.
The kinds `UntypedBool`, `UntypedInt` and so on represent
the six kinds of "untyped" constant types: boolean, integer, rune,
float, complex, and string.
The kind `UntypedNil` represents the type of the predeclared
`nil` value.
And the kind `Invalid` indicates the invalid type, which is used
for expressions containing errors, or for objects without types, like
`Label`, `Builtin`, or `PkgName`.
The `Name` method returns the name of the type, such as
`"float64"`, and the `Info` method returns a bitfield that
encodes information about the type, such as whether it is signed or
unsigned, integer or floating point, or real or complex.
`Typ` is a table of canonical basic types, indexed by
kind, so `Typ[String]` returns the `*Basic` that represents
`string`, for instance.
Like `Universe`, `Typ` is logically a constant, so don't
modify it.
A few minor subtleties:
According to the Go spec, pre-declared types such as `int` are
named types for the purposes of assignability, even though the type
checker does not represent them using `Named`.
And `unsafe.Pointer` is a pointer type for the purpose of
determining whether the receiver type of a method is legal, even
though the type checker does not represent it using `Pointer`.
The "untyped" types are usually only ascribed to constant expressions,
but there is one exception.
A comparison `x==y` has type "untyped bool", so the result of
this expression may be assigned to a variable of type `bool` or
any other named boolean type.
## Simple Composite Types
The types `Pointer`, `Array`, `Slice`, `Map`,
and `Chan` are pretty self-explanatory.
All have an `Elem` method that returns the element type `T`
for a pointer `*T`, an array `[n]T`, a slice `[]T`, a
map `map[K]T`, or a channel `chan T`.
This should feel familiar if you've used the `reflect.Value` API.
In addition, the `*Map`, `*Chan`, and `*Array` types
have accessor methods that return their key type, direction, and
length, respectively:
func (*Map) Key() Type
func (*Chan) Dir() ChanDir // = Send | Recv | SendRecv
func (*Array) Len() int64
## Struct Types
A struct type has an ordered list of fields and a corresponding
ordered list of field tags.
type Struct struct{ ... }
func (*Struct) NumFields() int
func (*Struct) Field(i int) *Var
func (*Struct) Tag(i int) string
Each field is a `Var` object whose `IsField` method returns true.
Field objects have no `Parent` scope, because they are
resolved through selections, not through the lexical environment.
<!-- TODO check this -->
Thanks to embedding, the expression `new(S).f` may be a shorthand
for a longer expression such as `new(S).d.e.f`, but in the
representation of `Struct` types, these field selection
operations are explicit.
That is, the set of fields of struct type `S` does not include `f`.
An anonymous field is represented like a regular field, but its
`Anonymous` method returns true.
One subtlety is relevant to tools that generate documentation.
When analyzing a declaration such as this,
type T struct{x int}
it may be tempting to consider the `Var` object for field `x` as if it
had the name `"T.x"`, but beware: field objects do not have
canonical names and there is no way to obtain the name `"T"`
from the `Var` for `x`.
That's because several types may have the same underlying struct type,
as in this code:
type T struct{x int}
type U T
Here, the `Var` for field `x` belongs equally to `T`
and to `U`, and short of inspecting source positions or walking
the AST---neither of which is possible for objects loaded from compiler
export data---it is not possible to ascertain that `x` was declared as
part of `T`.
The type checker builds the exact same data structures given this input:
type T U
type U struct{x int}
A similar issue applies to the methods of named interface types.
## Tuple Types
Like a struct, a tuple type has an ordered list of fields, and fields
may be named.
type Tuple struct{ ... }
func (*Tuple) Len() int
func (*Tuple) At(i int) *Var
Although tuples are not the type of any variable in Go, they are
the type of some expressions, such as the right-hand sides of these
assignments:
v, ok = m[key]
v, ok = <-ch
v, ok = x.(T)
f, err = os.Open(filename)
Tuples also represent the types of the parameter list and the result
list of a function, as we will see.
Since empty tuples are common, the nil `*Tuple` pointer is a valid empty tuple.
## Function and Method Types
The types of functions and methods are represented by a `Signature`,
which has a tuple of parameter types and a tuple of result types.
type Signature struct{ ... }
func (*Signature) Recv() *Var
func (*Signature) Params() *Tuple
func (*Signature) Results() *Tuple
func (*Signature) Variadic() bool
Variadic functions such as `fmt.Println` have the `Variadic`
flag set.
The final parameter of such functions is always a slice, or in the
special case of certain calls to `append`, a string.
A `Signature` for a method, whether concrete or abstract, has a
non-nil receiver parameter, `Recv`.
The type of the receiver is usually a named type or a pointer to a named type,
but it may be an unnamed struct or interface type in some cases.
Method types are rather second-class: they are only used for the
`Func` objects created by method declarations, and no Go
expression has a method type.
When printing a method type, the receiver does not appear, and the
`Identical` predicate ignores the receiver.
The types of `Builtin` objects like `append` cannot be
expressed as a `Signature` since those types require parametric
polymorphism.
`Builtin` objects are thus ascribed the `Invalid` basic type.
However, the type of each _call_ to a built-in function has a specific
and expressible Go type.
These types are recorded during type checking for later use
([TypeAndValue](#typeandvalue)).
## Named Types
Type declarations come in two forms.
The simplest kind, introduced in Go 1.9,
merely declares a (possibly alternative) name for an existing type.
Type names used in this way are informally called _type aliases_.
For example, this declaration lets you use the type
`Dictionary` as an alias for `map[string]string`:
type Dictionary = map[string]string
The declaration creates a `TypeName` object for `Dictionary`. The
object's `IsAlias` method returns true, and its `Type` method returns
a `Map` type that represents `map[string]string`.
The second form of type declaration, and the only kind prior to Go
1.9, does not use an equals sign:
type Celsius float64
This declaration does more than just give a name to a type.
It first defines a new `Named` type
whose underlying type is `float64`; this `Named` type is different
from any other type, including `float64`. The declaration binds the
`TypeName` object to the `Named` type.
Since Go 1.9, the Go language specification has used the term _defined
types_ instead of named types;
the essential property of a defined type is not that it has a name,
but that it is a distinct type with its own method set.
However, the type checker API predates that
change and instead calls defined types "named" types.
type Named struct{ ... }
func (*Named) NumMethods() int
func (*Named) Method(i int) *Func
func (*Named) Obj() *TypeName
func (*Named) Underlying() Type
The `Named` type's `Obj` method returns the `TypeName` object, which
provides the name, position, and other properties of the declaration.
Conversely, the `TypeName` object's `Type` method returns the `Named` type.
A `Named` type may appear as the receiver type in a method declaration.
Methods are associated with the `Named` type, not the name (the
`TypeName` object); it's possible---though cryptic---to declare a
method on a `Named` type using one of its aliases.
The `NumMethods` and `Method` methods enumerate the declared
methods associated with this `Named` type (or a pointer to it),
in the order they were declared.
However, due to the subtleties of anonymous fields and the difference
between value and pointer receivers, a named type may have more or fewer
methods than this list. We'll return to this in [Method Sets](#method-sets).
Every `Type` has an `Underlying` method, but for all of them
except `*Named`, it is simply the identity function.
For a named type, `Underlying` returns its underlying type, which
is always an unnamed type.
Thus `Underlying` returns `int` for both `T` and
`U` below.
type T int
type U T
Clients of the type checker often use type assertions or type switches
with a `Type` operand.
When doing so, it is often necessary to switch on the type that
_underlies_ the type of interest, and failure to do so may be a
bug.
This is a common pattern:
// handle types of composite literal
switch u := t.Underlying().(type) {
case *Struct: // ...
case *Map: // ...
case *Array, *Slice: // ...
default:
panic("impossible")
}
## Interface Types
Interface types are represented by `Interface`.
type Interface struct{ ... }
func (*Interface) Empty() bool
func (*Interface) NumMethods() int
func (*Interface) Method(i int) *Func
func (*Interface) NumEmbeddeds() int
func (*Interface) Embedded(i int) *Named
func (*Interface) NumExplicitMethods() int
func (*Interface) ExplicitMethod(i int) *Func
Syntactically, an interface type has a list of explicitly declared
methods (`ExplicitMethod`), and a list of embedded named
interface types (`Embedded`), but many clients care only about
the complete set of methods, which can be enumerated via
`Method`.
All three lists are ordered by name.
Since the empty interface is an important special case, the
`Empty` predicate provides a shorthand for `NumMethods() ==
0`.
As with the fields of structs (see above), the methods of interfaces
may belong equally to more than one interface type.
The `Func` object for method `f` in the code below is shared
by `I` and `J`:
type I interface { f() }
type J I
Because the difference between interface (abstract) and
non-interface (concrete) types is so important in Go, the
`IsInterface` predicate is provided for convenience.
func IsInterface(Type) bool
The type checker provides three utility methods relating to interface
satisfaction:
func Implements(V Type, T *Interface) bool
func AssertableTo(V *Interface, T Type) bool
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
The `Implements` predicate reports whether a type satisfies an
interface type.
`MissingMethod` is like `Implements`, but instead of
returning false, it explains why a type does not satisfy the
interface, for use in diagnostics.
`AssertableTo` reports whether a type assertion `v.(T)` is legal.
If `T` is a concrete type that doesn't have all the methods of
interface `v`, then the type assertion is not legal, as in this example:
// error: io.Writer is not assertible to int
func f(w io.Writer) int { return w.(int) }
## TypeAndValue
The type checker records the type of each expression in another field
of the `Info` struct, namely `Types`:
type Info struct {
...
Types map[ast.Expr]TypeAndValue
}
No entries are recorded for identifiers since the `Defs` and
`Uses` maps provide more information about them.
Also, no entries are recorded for pseudo-expressions like
`*ast.KeyValuePair` or `*ast.Ellipsis`.
The value of the `Types` map is a `TypeAndValue`, which
(unsurprisingly) holds the type and value of the expression, and in
addition, its _mode_.
The mode is opaque, but has predicates to answer questions such as:
Does this expression denote a value or a type? Does this value have an
address? Does this expression appear on the left-hand side of an
assignment? Does this expression appear in a context that expects two
results?
The comments in the code below give examples of expressions that
satisfy each predicate.
type TypeAndValue struct {
Type Type
Value constant.Value // for constant expressions only
...
}
func (TypeAndValue) IsVoid() bool // e.g. "main()"
func (TypeAndValue) IsType() bool // e.g. "*os.File"
func (TypeAndValue) IsBuiltin() bool // e.g. "len(x)"
func (TypeAndValue) IsValue() bool // e.g. "*os.Stdout"
func (TypeAndValue) IsNil() bool // e.g. "nil"
func (TypeAndValue) Addressable() bool // e.g. "a[i]" but not "f()", "m[key]"
func (TypeAndValue) Assignable() bool // e.g. "a[i]", "m[key]"
func (TypeAndValue) HasOk() bool // e.g. "<-ch", "m[key]"
The statement below inspects every expression within the AST of a single
type-checked file and prints its type, value, and mode:
%include typeandvalue/main.go inspect
It makes use of these two helper functions, which are not shown:
// nodeString formats a syntax tree in the style of gofmt.
func nodeString(n ast.Node) string
// mode returns a string describing the mode of an expression.
func mode(tv types.TypeAndValue) string
Given this input:
%include typeandvalue/main.go input -
the program prints:
%include typeandvalue/main.go output -
Notice that the identifiers for the built-ins `make` and
`print` have types that are specific to the particular calls in
which they appear.
Also notice `m["hello"]` has a 2-tuple type `(int, bool)`
and that it is assignable, but unlike the variable `m`, it is not
addressable.
Download the example and vary the inputs and see what the program prints.
Here's another example, adapted from the `govet` static checking tool.
It checks for accidental uses of a method value `x.f` when a
call `x.f()` was intended;
comparing a method `x.f` against nil is a common mistake.
%include nilfunc/main.go
Given this input,
%include nilfunc/main.go input -
the program reports these errors:
%include nilfunc/main.go output -
# Selections
A _selection_ is an expression _`expr`_`.f` in which
`f` denotes either a struct field or a method.
A selection is resolved not by looking for a name in the lexical
environment, but by looking within a _type_.
The type checker ascertains the meaning of each selection in the
package---a surprisingly tricky business---and records it in the
`Selections` mapping of the `Info` struct, whose values are
of type `Selection`:
type Selection struct{ ... }
func (s *Selection) Kind() SelectionKind // = FieldVal | MethodVal | MethodExpr
func (s *Selection) Recv() Type
func (s *Selection) Obj() Object
func (s *Selection) Type() Type
func (s *Selection) Index() []int
func (s *Selection) Indirect() bool
The `Kind` method discriminates between the three (legal) kinds
of selections, as indicated by the comments below.
type T struct{Field int}
func (T) Method() {}
var v T
// Kind Type
var _ = v.Field // FieldVal int
var _ = v.Method // MethodVal func()
var _ = T.Method // MethodExpr func(T)
Because of embedding, a selection may denote more than one field or
method, in which case it is ambiguous, and no `Selection` is
recorded for it.
The `Obj` method returns the `Object` for the selected field
(`*Var`) or method (`*Func`).
Due to embedding, the object may belong to a different type than that
of the receiver expression _`expr`_.
The `Type` method returns the type of the selection. For a field
selection, this is the type of the field, but for method selections,
the result is a function type that is not the same as the type of the
method.
For a `MethodVal`, the receiver parameter is dropped, and
for a `MethodExpr`, the receiver parameter becomes a regular
parameter, as shown in the example above.
The `Index` and `Indirect` methods report information about
implicit operations occurring during the selection that a compiler
would need to know about.
Because of embedding, a selection _`expr`_`.f` may be
shorthand for a sequence containing several implicit field selections,
_`expr`_`.d.e.f`, and `Index` reports the complete
sequence.
And because of automatic pointer dereferencing during struct field
accesses and method calls, a selection may imply one or more indirect
loads from memory; `Indirect` reports whether this occurs.
Clients of the type checker can call `LookupFieldOrMethod` to
look up a name within a type, as if by a selection.
This function has an intimidating signature, but conceptually it
accepts just a `Type` and a name, and returns a `Selection`:
func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) \
(obj Object, index []int, indirect bool)
The result is not actually a `Selection`, but it contains the
three main components of one: `Obj`, `Index`,
and `Indirect`.
The `addressable` flag should be set if the receiver is a
_variable_ of type `T`, since in a method selection on a
variable, an implicit address-of operation (`&`) may occur.
The flag indicates whether the methods of type `*T` should be
considered during the lookup.
(You may wonder why this parameter is necessary. Couldn't clients
instead call `LookupFieldOrMethod` on the pointer type `*T`
if the receiver is a `T` variable? The answer is that if
`T` is an interface type, the type `*T` has no methods at
all.)
The final two parameters of `LookupFieldOrMethod` are `(pkg
*Package, name string)`.
Together they specify the name of the field or method to look up.
This brings us to `Id`s.
# Ids
`LookupFieldOrMethod`'s need for a `Package` parameter
is a subtle consequence of the
[_Uniqueness of identifiers_](https://golang.org/ref/spec#Uniqueness_of_identifiers)
section in the Go spec: "Two
identifiers are different if they are spelled differently, or if they
appear in different packages and are not exported."
In practical terms, this means that a type may have two methods
(or two fields, or one of each) both named `f` so long as those
methods are defined in different packages, as in this example:
package a
type A int
func (A) f()
package b
type B int
func (B) f()
package c
import ( "a"; "b" )
type C struct{a.A; b.B} // C has two methods called f
The type `c.C` has two methods named `f`, but there is
no ambiguity because the two `f`s are distinct
identifiers---think of them as `fᵃ` and `fᵇ`.
For an exported method, this situation _would_ be ambiguous
because there is no distinction between `Fᵃ` and `Fᵇ`; there
is only `F`.
Despite having two methods called `f`, neither of them can be
called from within package `c` because `c` has no way to
identify them.
Within `c`, `f` is the identifier `fᶜ`, and
type `C` has no method of that name.
But if we pass an instance of `C` to code in package `a`
and call its `f` method via an interface, `fᵃ` is called.
The practical consequence for tool builders is that any time you need
to look up a field or method by name, or construct a map of fields and/or
methods keyed by name, it is not sufficient to use the object's name
as a key.
Instead, you must call the `Object.Id` method, which returns
a string that incorporates the object name, and for unexported
objects, the package path too.
There is also a standalone function `Id` that combines a name and
the package path in the same way:
func Id(pkg *Package, name string) string
This distinction applies to selections _`expr`_`.f`, but not
to lexical references `x` because for unexported identifiers,
declarations and references always appear in the same package.
Fun fact: the `reflect.StructField` type records both the
`Name` and the `PkgPath` strings for the same reason.
The `FieldByName` methods of `reflect.Value` and
`reflect.Type` match field names without regard to the package.
If there is more than one match, they return an invalid value.
# Method Sets
The _method set_ of a type is the set of methods that can be
called on any value of that type.
(A variable of type `T` has access to all the methods of type
`*T` as well, due to the implicit address-of operation during
method calls, but those extra methods are not part of the method set
of `T`.)
Clients can request the method set of a type `T` by calling
`NewMethodSet(T)`:
type MethodSet struct{ ... }
func NewMethodSet(T Type) *MethodSet
func (s *MethodSet) Len() int
func (s *MethodSet) At(i int) *Selection
func (s *MethodSet) Lookup(pkg *Package, name string) *Selection
The `Len` and `At` methods access a list of
`Selections`, all of kind `MethodVal`, ordered by `Id`.
The `Lookup` function allows lookup of a single method by
name (and package path, as explained in the previous section).
`NewMethodSet` can be expensive, so for applications that compute
method sets repeatedly, `golang.org/x/tools/go/types/typeutil`
provides a `MethodSetCache` type that records previous results.
If you only need a single method, don't construct the
`MethodSet` at all; it's cheaper to use
`LookupFieldOrMethod`.
The next program generates a boilerplate
declaration of a new concrete type that satisfies an existing
interface.
Here's an example:
%include skeleton/main.go output1 -
The three arguments are the package and the name of the existing
interface type, and the name of the new concrete type.
The `main` function (not shown) loads the specified package and
calls `PrintSkeleton` with the remaining two arguments:
%include skeleton/main.go
First, `PrintSkeleton` locates the package-level named interface
type, handling various error cases.
Then it chooses the name for the receiver of the new methods: the
first letter of the concrete type.
Finally, it iterates over the method set of the interface, printing
the corresponding concrete method declarations.
There's a subtlety in the declaration of `sig`, which is the
string form of the method signature.
We could have obtained this string from `meth.Type().String()`,
but this would cause any named types within it to be formatted with
the complete package path, for instance
`net/http.ResponseWriter`, which is informative in diagnostics
but not legal Go syntax.
The `TypeString` function (explained in [Formatting Values](#formatting-values)) allows the
caller to control how packages are printed.
Passing `(*types.Package).Name` causes only the package name
`http` to be printed, not the complete path.
Here's another example that illustrates it:
%include skeleton/main.go output2 -
The following program inspects all pairs of package-level named types
in `pkg`, and reports the types that satisfy each interface type.
%include implements/main.go implements
Given this input,
%include implements/main.go input
the program prints:
%include implements/main.go output -
Notice that the method set of `B` does not include `g`, but
the method set of `*B` does.
That's why we needed the second assignability check, using the pointer
type `types.NewPointer(T)`.
# Constants
A constant expression is one whose value is guaranteed to be computed at
compile time.
Constant expressions may appear in types, specifically as the length
of an array type such as `[16]byte`, so one of the jobs of the
type checker is to compute the value of each constant expression.
As we saw in the `typeandvalue` example, the type checker records
the value of each constant expression like `"Hello, " + "world"`,
storing it in the `Value` field of the `TypeAndValue` struct.
Constants are represented using the `Value` interface from the
`go/constant` package.
package constant // go/constant
type Value interface {
Kind() Kind
}
type Kind int // one of Unknown, Bool, String, Int, Float, Complex
The interface has only one method, for discriminating the various
kinds of constants, but the package provides many functions for
inspecting a value of a known kind,
// Accessors
func BoolVal(x Value) bool
func Float32Val(x Value) (float32, bool)
func Float64Val(x Value) (float64, bool)
func Int64Val(x Value) (int64, bool)
func StringVal(x Value) string
func Uint64Val(x Value) (uint64, bool)
func Bytes(x Value) []byte
func BitLen(x Value) int
func Sign(x Value) int
for performing arithmetic on values,
// Operations
func Compare(x Value, op token.Token, y Value) bool
func UnaryOp(op token.Token, y Value, prec uint) Value
func BinaryOp(x Value, op token.Token, y Value) Value
func Shift(x Value, op token.Token, s uint) Value
func Denom(x Value) Value
func Num(x Value) Value
func Real(x Value) Value
func Imag(x Value) Value
and for constructing new values:
// Constructors
func MakeBool(b bool) Value
func MakeFloat64(x float64) Value
func MakeFromBytes(bytes []byte) Value
func MakeFromLiteral(lit string, tok token.Token, prec uint) Value
func MakeImag(x Value) Value
func MakeInt64(x int64) Value
func MakeString(s string) Value
func MakeUint64(x uint64) Value
func MakeUnknown() Value
All numeric `Value`s, whether integer or floating-point, signed or
unsigned, or real or complex, are represented more precisely than
ordinary Go types like `int64` and `float64`.
Internally, the `go/constant` package uses multi-precision data types
like `Int`, `Rat`, and `Float` from the `math/big` package so that
`Values` and their arithmetic operations are accurate to at least 256
bits, as required by the Go specification.
<!-- TODO example -->
# Size and Alignment
Because the calls `unsafe.Sizeof(v)`, `unsafe.Alignof(v)`,
and `unsafe.Offsetof(v.f)` are all constant expressions, the type
checker must be able to compute the memory layout of any value
`v`.
By default, the type checker uses the same layout algorithm as the Go
1.5 `gc` compiler targeting `amd64`.
Clients can configure the type checker to use a different algorithm by
providing an instance of the `types.Sizes` interface in the
`types.Config` struct:
package types
type Sizes interface {
Alignof(T Type) int64
Offsetsof(fields []*Var) []int64
Sizeof(T Type) int64
}
For common changes, like reducing the word size to 32 bits, clients
can use an instance of `StdSizes`:
type StdSizes struct {
WordSize int64
MaxAlign int64
}
This type has two basic size and alignment parameters from which it
derives all the other values using common assumptions.
For example, pointers, functions, maps, and channels fit in one word,
strings and interfaces require two words, and slices need three.
The default behaviour is equivalent to `StdSizes{8, 8}`.
For more esoteric layout changes, you'll need to write a new
implementation of the `Sizes` interface.
The `hugeparam` program below prints all function parameters and
results whose size exceeds a threshold.
By default, the threshold is 48 bytes, but you can set it via the
`-bytes` command-line flag.
Such a tool could help identify inefficient parameter passing in your
programs.
%include hugeparam/main.go
As before, `Inspect` applies a function to every node in the AST.
The function cares about two kinds of nodes: declarations of named
functions and methods (`*ast.FuncDecl`) and function literals
(`*ast.FuncLit`).
Observe the two cases' different logic to obtain the type of each
function.
Here's a typical invocation on the standard `encoding/xml` package.
It reports a number of places where the 7-word
[`StartElement` type](https://pkg.go.dev/encoding/xml#StartElement)
is copied.
%include hugeparam/main.go output -
# Imports
The type checker's `Check` function processes a slice of parsed
files (`[]*ast.File`) that make up one package.
When the type checker encounters an import declaration, it needs the
type information for the objects in the imported package.
It gets it by calling the `Import` method of the `Importer`
interface shown below, an instance of which must be provided by the
`Config`.
This separation of concerns relieves the type checker from having to
know any of the details of Go workspace organization, `GOPATH`,
compiler file formats, and so on.
type Importer interface {
Import(path string) (*Package, error)
}
Most of our examples used the simplest `Importer` implementation,
`importer.Default()`, provided by the `go/importer` package.
This importer looks in `$GOROOT` and `$GOPATH` for `.a`
files written by the compiler (`gc` or `gccgo`)
that was used to build the program.
In addition to object code, these files contain _export data_,
that is, a description of all the objects declared by the package, and
also of any objects from other packages that were referred to indirectly.
Because export data includes information about dependencies, the type
checker need load at most one file per import, instead of one per
transitive dependency.
Compiler export data is compact and efficient to locate, load, and
parse, but it has several shortcomings.
First, it does not contain position information for imported
objects, reducing the quality of certain diagnostic messages.
Second, it does not contain complete syntax trees nor semantic information
about the contents of function bodies, so it is not suitable for
interprocedural analyses.
Third, compiler object data may be stale. Nothing detects or ensures
that the object files are more recent than the source files from which
they were derived.
Generally, object data for standard packages is likely to be
up-to-date, but for user packages, it depends on how recently the user
ran a `go install` or `go build -i` command.
The [`golang.org/tools/x/go/packages`
package](https://pkg.go.dev/golang.org/x/tools/go/packages) provides
a comprehensive means of loading packages from source.
It runs `go list` to query the project metadata,
performs [`cgo`](https://golang.org/cmd/cgo/cgo) preprocessing if necessary,
reads and parses the source files,
and optionally type-checks each package.
It can load a whole program from source, or load just the initial
packages from source and load all their dependencies from export data.
It loads independent packages in parallel to hide I/O latency, and
detects and reports import cycles.
For each package, it provides the `types.Package` containing the
package's lexical environment, the list of `ast.File` syntax
trees for each file in the package, the `types.Info` containing
type information for each syntax node, a list of type errors
associated with that package, and other information too.
Since some of this information is more costly to compute,
the API allows you to select which parts you need,
but since this is a tutorial we'll generally request complete
information so that it is easier to explore.
The `doc` program below demonstrates a simple use of `go/packages`.
It is a rudimentary implementation of `go doc` that prints the type,
methods, and documentation of the package-level object specified on
the command line.
Here's an example:
%include doc/main.go output -
Observe that it prints the correct location of each method
declaration, even though, due to embedding, some of
`http.File`'s methods were declared in another package.
Here's the first part of the program, showing how to load
complete type information including typed syntax,
for a single package `pkgpath`,
plus exported type information for its dependencies.
%include doc/main.go part1
By default, `go/packages`, instructs the parser to retain comments during parsing.
The rest of the program prints the output:
%include doc/main.go part2
We used `IntuitiveMethodSet` to compute the method set, instead
of `NewMethodSet`.
The result of this convenience function, which is intended for use in
user interfaces, includes methods of `*T` as well as those of
`T`, since that matches most users' intuition about the method
set of a type.
(Our example, `http.File`, didn't illustrate the difference, but try
running it on a type with both value and pointer methods.)
Also notice `PathEnclosingInterval`, which finds the set of AST
nodes that enclose a particular point, in this case, the object's
declaring identifier.
By walking up with path, we find the enclosing declaration, to which
the documentation is attached.
# Formatting support
All types that satisfy `Type` or `Object` define a
`String` method that formats the type or object in a readable
notation. `Selection` also provides a `String` method.
All package-level objects within these data structures are
printed with the complete package path, as in these examples:
[]encoding/json.Marshaler // a *Slice type
encoding/json.Marshal // a *Func object
(*encoding/json.Encoder).Encode // a *Func object (method)
func (enc *encoding/json.Encoder) Encode(v interface{}) error // a method *Signature
func NewEncoder(w io.Writer) *encoding/json.Encoder // a function *Signature
This notation is unambiguous, but it is not legal Go syntax.
Also, package paths may be long, and the same package path may appear
many times in a single string, for instance, when formatting a
function of several parameters.
Because these strings often form part of a tool's user interface---as
with the diagnostic messages of `hugeparam` or the code generated
by `skeleton`---many clients want more control over the
formatting of package names.
The `go/types` package provides these alternatives to the
`String` methods:
func ObjectString(obj Object, qf Qualifier) string
func TypeString(typ Type, qf Qualifier) string
func SelectionString(s *Selection, qf Qualifier) string
type Qualifier func(*Package) string
The `TypeString`, `ObjectString`, and `SelectionString`
functions are like the `String` methods of the respective types,
but they accept an additional argument, a `Qualifier`.
A `Qualifier` is a client-provided function that determines how a
package name is rendered as a string.
If it is nil, the default behavior is to print the package's
path, just like the `String` methods do.
If a caller passes `(*Package).Name` as the qualifier, that is, a
function that accepts a package and returns its `Name`, then
objects are qualified only by the package name.
The above examples would look like this:
[]json.Marshaler
json.Marshal
(*json.Encoder).Encode
func (enc *json.Encoder) Encode(v interface{}) error
func NewEncoder(w io.Writer) *json.Encoder
Often when a tool prints some output, it is implicitly in the
context of a particular package, perhaps one specified by the
command line or HTTP request.
In that case, it is more natural to omit the package qualification
altogether for objects belonging to that package, but to qualify all
other objects by their package's path.
That's what the `RelativeTo(pkg)` qualifier does:
func RelativeTo(pkg *Package) Qualifier
The examples below show how `json.NewEncoder` would be printed
using three qualifiers, each relative to a different package:
// RelativeTo "encoding/json":
func NewEncoder(w io.Writer) *Encoder
// RelativeTo "io":
func NewEncoder(w Writer) *encoding/json.Encoder
// RelativeTo any other package:
func NewEncoder(w io.Writer) *encoding/json.Encoder
Another qualifier that may be relevant to refactoring tools (but is
not currently provided by the type checker) is one that renders each
package name using the locally appropriate name within a given source
file.
Its behavior would depend on the set of import declarations, including
renaming imports, within that source file.
# Getting from A to B
The type checker and its related packages represent many aspects of a
Go program in many different ways, and analysis tools must often map
between them.
For instance, a named entity may be identified by its `Object`;
by its declaring identifier (`ast.Ident`) or by any referring
identifier; by its declaring `ast.Node`; by the position
(`token.Pos`) of any those nodes; or by the filename and
line/column number (or byte offset) of those `token.Pos` values.
In this section, we'll list solutions to a number of common problems
of the form "I have an A; I need the corresponding B".
To map **from a `token.Pos` to an `ast.Node`**, call the
helper function
[`astutil.PathEnclosingInterval`](https://pkg.go.dev/golang.org/x/tools/go/ast/astutil#PathEnclosingInterval).
It returns the enclosing `ast.Node`, and all its ancestors up to
the root of the file.
If you don't know which file `*ast.File` the `token.Pos` belongs to,
you can iterate over the parsed files of the package and quickly test
whether its position falls within the file's range,
from `File.FileStart` to `File.FileEnd`.
To map **from an `Object` to its declaring syntax**, call
`Pos` to get its position, then use `PathEnclosingInterval` as before.
This approach is suitable for a one-off query. For repeated use, it
may be more efficient to visit the syntax tree and construct the
mapping between declarations and objects.
To map **from an `ast.Ident` to the `Object`** it refers to (or
declares), consult the `Uses` or `Defs` map for the
package, as shown in [Identifier Resolution](#identifier-resolution).
To map **from an `Object` to its documentation**, find the
object's declaration, and look at the attached `Doc` field.
You must have set the parser's `ParseComments` flag.
See the `doc` example in [Imports](#imports).
|
gotypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/gen.go
|
//go:generate bash -c "go run ../internal/cmd/weave/weave.go ./go-types.md > README.md"
package gotypes
|
lookup
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/lookup/lookup.go
|
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"strings"
)
// !+input
const hello = `
package main
import "fmt"
// append
func main() {
// fmt
fmt.Println("Hello, world")
// main
main, x := 1, 2
// main
print(main, x)
// x
}
// x
`
//!-input
// !+main
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
// Each comment contains a name.
// Look up that name in the innermost scope enclosing the comment.
for _, comment := range f.Comments {
pos := comment.Pos()
name := strings.TrimSpace(comment.Text())
fmt.Printf("At %s,\t%q = ", fset.Position(pos), name)
inner := pkg.Scope().Innermost(pos)
if _, obj := inner.LookupParent(name, pos); obj != nil {
fmt.Println(obj)
} else {
fmt.Println("not found")
}
}
}
//!-main
/*
//!+output
$ go build golang.org/x/example/gotypes/lookup
$ ./lookup
At hello.go:6:1, "append" = builtin append
At hello.go:8:9, "fmt" = package fmt
At hello.go:10:9, "main" = func cmd/hello.main()
At hello.go:12:9, "main" = var main int
At hello.go:14:9, "x" = var x int
At hello.go:16:1, "x" = not found
//!-output
*/
|
implements
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/implements/main.go
|
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `package main
type A struct{}
func (*A) f()
type B int
func (B) f()
func (*B) g()
type I interface { f() }
type J interface { g() }
`
//!-input
func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
//!+implements
// Find all named types at package level.
var allNamed []*types.Named
for _, name := range pkg.Scope().Names() {
if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {
allNamed = append(allNamed, obj.Type().(*types.Named))
}
}
// Test assignability of all distinct pairs of
// named types (T, U) where U is an interface.
for _, T := range allNamed {
for _, U := range allNamed {
if T == U || !types.IsInterface(U) {
continue
}
if types.AssignableTo(T, U) {
fmt.Printf("%s satisfies %s\n", T, U)
} else if !types.IsInterface(T) &&
types.AssignableTo(types.NewPointer(T), U) {
fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U)
}
}
}
//!-implements
}
/*
//!+output
$ go build golang.org/x/example/gotypes/implements
$ ./implements
*hello.A satisfies hello.I
hello.B satisfies hello.I
*hello.B satisfies hello.J
//!-output
*/
|
typeandvalue
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/typeandvalue/main.go
|
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `
package main
var m = make(map[string]int)
func main() {
v, ok := m["hello, " + "world"]
print(rune(v), ok)
}
`
//!-input
var fset = token.NewFileSet()
func main() {
f, err := parser.ParseFile(fset, "hello.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
//!+inspect
// f is a parsed, type-checked *ast.File.
ast.Inspect(f, func(n ast.Node) bool {
if expr, ok := n.(ast.Expr); ok {
if tv, ok := info.Types[expr]; ok {
fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv))
fmt.Printf("\t\t\t\ttype: %v\n", tv.Type)
if tv.Value != nil {
fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value)
}
}
}
return true
})
//!-inspect
}
// nodeString formats a syntax tree in the style of gofmt.
func nodeString(n ast.Node) string {
var buf bytes.Buffer
format.Node(&buf, fset, n)
return buf.String()
}
// mode returns a string describing the mode of an expression.
func mode(tv types.TypeAndValue) string {
s := ""
if tv.IsVoid() {
s += ",void"
}
if tv.IsType() {
s += ",type"
}
if tv.IsBuiltin() {
s += ",builtin"
}
if tv.IsValue() {
s += ",value"
}
if tv.IsNil() {
s += ",nil"
}
if tv.Addressable() {
s += ",addressable"
}
if tv.Assignable() {
s += ",assignable"
}
if tv.HasOk() {
s += ",ok"
}
return s[1:]
}
/*
//!+output
$ go build golang.org/x/example/gotypes/typeandvalue
$ ./typeandvalue
make(map[string]int) mode: value
type: map[string]int
make mode: builtin
type: func(map[string]int) map[string]int
map[string]int mode: type
type: map[string]int
string mode: type
type: string
int mode: type
type: int
m["hello, "+"world"] mode: value,assignable,ok
type: (int, bool)
m mode: value,addressable,assignable
type: map[string]int
"hello, " + "world" mode: value
type: string
value: "hello, world"
"hello, " mode: value
type: untyped string
value: "hello, "
"world" mode: value
type: untyped string
value: "world"
print(rune(v), ok) mode: void
type: ()
print mode: builtin
type: func(rune, bool)
rune(v) mode: value
type: rune
rune mode: type
type: rune
...more not shown...
//!-output
*/
|
nilfunc
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/nilfunc/main.go
|
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `package main
import "bytes"
func main() {
var buf bytes.Buffer
if buf.Bytes == nil && bytes.Repeat != nil && main == nil {
// ...
}
}
`
//!-input
var fset = token.NewFileSet()
func main() {
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Types: make(map[ast.Expr]types.TypeAndValue),
}
if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
ast.Inspect(f, func(n ast.Node) bool {
if n != nil {
CheckNilFuncComparison(info, n)
}
return true
})
}
// !+
// CheckNilFuncComparison reports unintended comparisons
// of functions against nil, e.g., "if x.Method == nil {".
func CheckNilFuncComparison(info *types.Info, n ast.Node) {
e, ok := n.(*ast.BinaryExpr)
if !ok {
return // not a binary operation
}
if e.Op != token.EQL && e.Op != token.NEQ {
return // not a comparison
}
// If this is a comparison against nil, find the other operand.
var other ast.Expr
if info.Types[e.X].IsNil() {
other = e.Y
} else if info.Types[e.Y].IsNil() {
other = e.X
} else {
return // not a comparison against nil
}
// Find the object.
var obj types.Object
switch v := other.(type) {
case *ast.Ident:
obj = info.Uses[v]
case *ast.SelectorExpr:
obj = info.Uses[v.Sel]
default:
return // not an identifier or selection
}
if _, ok := obj.(*types.Func); !ok {
return // not a function or method
}
fmt.Printf("%s: comparison of function %v %v nil is always %v\n",
fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)
}
//!-
/*
//!+output
$ go build golang.org/x/example/gotypes/nilfunc
$ ./nilfunc
input.go:7:5: comparison of function Bytes == nil is always false
input.go:7:25: comparison of function Repeat != nil is always true
input.go:7:48: comparison of function main == nil is always false
//!-output
*/
|
pkginfo
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/pkginfo/main.go
|
// !+
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}`
func main() {
fset := token.NewFileSet()
// Parse the input string, []byte, or io.Reader,
// recording position information in fset.
// ParseFile returns an *ast.File, a syntax tree.
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
// A Config controls various options of the type checker.
// The defaults work fine except for one setting:
// we must specify how to deal with imports.
conf := types.Config{Importer: importer.Default()}
// Type-check the package containing only file f.
// Check returns a *types.Package.
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
fmt.Printf("Package %q\n", pkg.Path())
fmt.Printf("Name: %s\n", pkg.Name())
fmt.Printf("Imports: %s\n", pkg.Imports())
fmt.Printf("Scope: %s\n", pkg.Scope())
}
//!-
/*
//!+output
$ go build golang.org/x/example/gotypes/pkginfo
$ ./pkginfo
Package "cmd/hello"
Name: main
Imports: [package fmt ("fmt")]
Scope: package "cmd/hello" scope 0x820533590 {
. func cmd/hello.main()
}
//!-output
*/
|
doc
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/doc/main.go
|
// The doc command prints the doc comment of a package-level object.
package main
import (
"fmt"
"go/ast"
"log"
"os"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
)
func main() {
if len(os.Args) != 3 {
log.Fatal("Usage: doc <package> <object>")
}
//!+part1
pkgpath, name := os.Args[1], os.Args[2]
// Load complete type information for the specified packages,
// along with type-annotated syntax.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
// Find the package and package-level object.
pkg := pkgs[0]
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
log.Fatalf("%s.%s not found", pkg.Types.Path(), name)
}
//!-part1
//!+part2
// Print the object and its methods (incl. location of definition).
fmt.Println(obj)
for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel)
}
// Find the path from the root of the AST to the object's position.
// Walk up to the enclosing ast.Decl for the doc comment.
for _, file := range pkg.Syntax {
pos := obj.Pos()
if !(file.FileStart <= pos && pos < file.FileEnd) {
continue // not in this file
}
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
fmt.Println("\n", n.Doc.Text())
return
case *ast.FuncDecl:
fmt.Println("\n", n.Doc.Text())
return
}
}
}
//!-part2
}
// (The $GOROOT below is the actual string that appears in file names
// loaded from export data for packages in the standard library.)
/*
//!+output
$ ./doc net/http File
type net/http.File interface{Readdir(count int) ([]os.FileInfo, error); Seek(offset int64, whence int) (int64, error); Stat() (os.FileInfo, error); io.Closer; io.Reader}
$GOROOT/src/io/io.go:92:2: method (net/http.File) Close() error
$GOROOT/src/io/io.go:71:2: method (net/http.File) Read(p []byte) (n int, err error)
/go/src/net/http/fs.go:65:2: method (net/http.File) Readdir(count int) ([]os.FileInfo, error)
$GOROOT/src/net/http/fs.go:66:2: method (net/http.File) Seek(offset int64, whence int) (int64, error)
/go/src/net/http/fs.go:67:2: method (net/http.File) Stat() (os.FileInfo, error)
A File is returned by a FileSystem's Open method and can be
served by the FileServer implementation.
The methods should behave the same as those on an *os.File.
//!-output
*/
|
hello
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/hello/hello.go
|
// !+
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
//!-
|
hugeparam
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/hugeparam/main.go
|
// The hugeparam command identifies by-value parameters that are larger than n bytes.
//
// Example:
//
// $ ./hugeparams encoding/xml
package main
import (
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"golang.org/x/tools/go/packages"
)
// !+
var bytesFlag = flag.Int("bytes", 48, "maximum parameter size in bytes")
func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {
checkTuple := func(descr string, tuple *types.Tuple) {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {
fmt.Printf("%s: %q %s: %s = %d bytes\n",
fset.Position(v.Pos()),
v.Name(), descr, v.Type(), sz)
}
}
}
checkSig := func(sig *types.Signature) {
checkTuple("parameter", sig.Params())
checkTuple("result", sig.Results())
}
for _, file := range files {
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.FuncDecl:
checkSig(info.Defs[n.Name].Type().(*types.Signature))
case *ast.FuncLit:
checkSig(info.Types[n.Type].Type.(*types.Signature))
}
return true
})
}
}
//!-
func main() {
flag.Parse()
// Load complete type information for the specified packages,
// along with type-annotated syntax and the "sizeof" function.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, flag.Args()...)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
for _, pkg := range pkgs {
PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax)
}
}
/*
//!+output
% ./hugeparam encoding/xml
/go/src/encoding/xml/marshal.go:167:50: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:734:97: "" result: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:761:51: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:781:68: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/xml.go:72:30: "" result: encoding/xml.StartElement = 56 bytes
//!-output
*/
|
defsuses
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/defsuses/main.go
|
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
`
// !+
func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
_, err := conf.Check("hello", fset, files, info)
if err != nil {
return err // type error
}
for id, obj := range info.Defs {
fmt.Printf("%s: %q defines %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
for id, obj := range info.Uses {
fmt.Printf("%s: %q uses %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
return nil
}
//!-
func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
if err := PrintDefsUses(fset, f); err != nil {
log.Fatal(err) // type error
}
}
/*
//!+output
$ go build golang.org/x/example/gotypes/defsuses
$ ./defsuses
hello.go:1:9: "main" defines <nil>
hello.go:5:6: "main" defines func hello.main()
hello.go:6:9: "fmt" uses package fmt
hello.go:6:13: "Println" uses func fmt.Println(a ...interface{}) (n int, err error)
//!-output
*/
|
skeleton
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/gotypes/skeleton/main.go
|
// The skeleton command prints the boilerplate for a concrete type
// that implements the specified interface type.
//
// Example:
//
// $ ./skeleton io ReadWriteCloser buffer
// // *buffer implements io.ReadWriteCloser.
// type buffer struct{ /* ... */ }
// func (b *buffer) Close() error { panic("unimplemented") }
// func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") }
// func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") }
package main
import (
"fmt"
"go/types"
"log"
"os"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/tools/go/packages"
)
const usage = "Usage: skeleton <package> <interface> <concrete>"
// !+
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {
obj := pkg.Scope().Lookup(ifacename)
if obj == nil {
return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename)
}
if _, ok := obj.(*types.TypeName); !ok {
return fmt.Errorf("%v is not a named type", obj)
}
iface, ok := obj.Type().Underlying().(*types.Interface)
if !ok {
return fmt.Errorf("type %v is a %T, not an interface",
obj, obj.Type().Underlying())
}
// Use first letter of type name as receiver parameter.
if !isValidIdentifier(concname) {
return fmt.Errorf("invalid concrete type name: %q", concname)
}
r, _ := utf8.DecodeRuneInString(concname)
fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename)
fmt.Printf("type %s struct{}\n", concname)
mset := types.NewMethodSet(iface)
for i := 0; i < mset.Len(); i++ {
meth := mset.At(i).Obj()
sig := types.TypeString(meth.Type(), (*types.Package).Name)
fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n",
r, concname, meth.Name(),
strings.TrimPrefix(sig, "func"))
}
return nil
}
//!-
func isValidIdentifier(id string) bool {
for i, r := range id {
if !unicode.IsLetter(r) &&
!(i > 0 && unicode.IsDigit(r)) {
return false
}
}
return id != ""
}
func main() {
if len(os.Args) != 4 {
log.Fatal(usage)
}
pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3]
// Load only exported type information for the specified package.
conf := &packages.Config{Mode: packages.NeedTypes}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil {
log.Fatal(err)
}
}
/*
//!+output1
$ ./skeleton io ReadWriteCloser buffer
// *buffer implements io.ReadWriteCloser.
type buffer struct{}
func (b *buffer) Close() error {
panic("unimplemented")
}
func (b *buffer) Read(p []byte) (n int, err error) {
panic("unimplemented")
}
func (b *buffer) Write(p []byte) (n int, err error) {
panic("unimplemented")
}
//!-output1
//!+output2
$ ./skeleton net/http Handler myHandler
// *myHandler implements net/http.Handler.
type myHandler struct{}
func (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) {
panic("unimplemented")
}
//!-output2
*/
|
outyet
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/outyet/main_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// statusHandler is an http.Handler that writes an empty response using itself
// as the response status code.
type statusHandler int
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(int(*h))
}
func TestIsTagged(t *testing.T) {
// Set up a fake "Google Code" web server reporting 404 not found.
status := statusHandler(http.StatusNotFound)
s := httptest.NewServer(&status)
defer s.Close()
if isTagged(s.URL) {
t.Fatal("isTagged == true, want false")
}
// Change fake server status to 200 OK and try again.
status = http.StatusOK
if !isTagged(s.URL) {
t.Fatal("isTagged == false, want true")
}
}
func TestIntegration(t *testing.T) {
status := statusHandler(http.StatusNotFound)
ts := httptest.NewServer(&status)
defer ts.Close()
// Replace the pollSleep with a closure that we can block and unblock.
sleep := make(chan bool)
pollSleep = func(time.Duration) {
sleep <- true
sleep <- true
}
// Replace pollDone with a closure that will tell us when the poller is
// exiting.
done := make(chan bool)
pollDone = func() { done <- true }
// Put things as they were when the test finishes.
defer func() {
pollSleep = time.Sleep
pollDone = func() {}
}()
s := NewServer("1.x", ts.URL, 1*time.Millisecond)
<-sleep // Wait for poll loop to start sleeping.
// Make first request to the server.
r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if b := w.Body.String(); !strings.Contains(b, "No.") {
t.Fatalf("body = %s, want no", b)
}
status = http.StatusOK
<-sleep // Permit poll loop to stop sleeping.
<-done // Wait for poller to see the "OK" status and exit.
// Make second request to the server.
w = httptest.NewRecorder()
s.ServeHTTP(w, r)
if b := w.Body.String(); !strings.Contains(b, "YES!") {
t.Fatalf("body = %q, want yes", b)
}
}
|
outyet
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/outyet/go.mod
|
module golang.org/x/example/outyet
go 1.19
|
outyet
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/outyet/main.go
|
// 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.
// Outyet is a web server that announces whether or not a particular Go version
// has been tagged.
package main
import (
"expvar"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"sync"
"time"
)
// Command-line flags.
var (
httpAddr = flag.String("http", "localhost:8080", "Listen address")
pollPeriod = flag.Duration("poll", 5*time.Second, "Poll period")
version = flag.String("version", "1.4", "Go version")
)
const baseChangeURL = "https://go.googlesource.com/go/+/"
func main() {
flag.Parse()
changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version)
http.Handle("/", NewServer(*version, changeURL, *pollPeriod))
log.Printf("serving http://%s", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}
// Exported variables for monitoring the server.
// These are exported via HTTP as a JSON object at /debug/vars.
var (
hitCount = expvar.NewInt("hitCount")
pollCount = expvar.NewInt("pollCount")
pollError = expvar.NewString("pollError")
pollErrorCount = expvar.NewInt("pollErrorCount")
)
// Server implements the outyet server.
// It serves the user interface (it's an http.Handler)
// and polls the remote repository for changes.
type Server struct {
version string
url string
period time.Duration
mu sync.RWMutex // protects the yes variable
yes bool
}
// NewServer returns an initialized outyet server.
func NewServer(version, url string, period time.Duration) *Server {
s := &Server{version: version, url: url, period: period}
go s.poll()
return s
}
// poll polls the change URL for the specified period until the tag exists.
// Then it sets the Server's yes field true and exits.
func (s *Server) poll() {
for !isTagged(s.url) {
pollSleep(s.period)
}
s.mu.Lock()
s.yes = true
s.mu.Unlock()
pollDone()
}
// Hooks that may be overridden for integration tests.
var (
pollSleep = time.Sleep
pollDone = func() {}
)
// isTagged makes an HTTP HEAD request to the given URL and reports whether it
// returned a 200 OK response.
func isTagged(url string) bool {
pollCount.Add(1)
r, err := http.Head(url)
if err != nil {
log.Print(err)
pollError.Set(err.Error())
pollErrorCount.Add(1)
return false
}
return r.StatusCode == http.StatusOK
}
// ServeHTTP implements the HTTP user interface.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hitCount.Add(1)
s.mu.RLock()
data := struct {
URL string
Version string
Yes bool
}{
s.url,
s.version,
s.yes,
}
s.mu.RUnlock()
err := tmpl.Execute(w, data)
if err != nil {
log.Print(err)
}
}
// tmpl is the HTML template that drives the user interface.
var tmpl = template.Must(template.New("tmpl").Parse(`
<!DOCTYPE html><html><body><center>
<h2>Is Go {{.Version}} out yet?</h2>
<h1>
{{if .Yes}}
<a href="{{.URL}}">YES!</a>
{{else}}
No. :-(
{{end}}
</h1>
</center></body></html>
`))
|
appengine-hello
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/app.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hello is a simple App Engine application that replies to requests
// on /hello with a welcoming message.
package hello
import (
"fmt"
"net/http"
)
// init is run before the application starts serving.
func init() {
// Handle all requests with path /hello with the helloHandler function.
http.HandleFunc("/hello", helloHandler)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from the Go app")
}
|
appengine-hello
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/README.md
|
This code is a starting point for your Google App Engine application in
Go.
To run the application locally you need the install the [Go Cloud
SDK](https://cloud.google.com/appengine/docs/go/#Go_tools) and execute the next
command from the directory containing this file:
$ goapp serve app.yaml
To deploy the application you have to first create an App Engine project
and use it as the application file in all the yaml files.
|
appengine-hello
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/app.yaml
|
# 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.
application: you-application-id
version: 1
runtime: go
api_version: go1
handlers:
- url: /hello
script: _go_app
- url: /favicon.ico
static_files: static/favicon.ico
upload: static/favicon.ico
- url: /
static_files: static/index.html
upload: static/index.html
- url: /
static_dir: static
|
static
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/static/style.css
|
/*
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.
*/
h1 {
text-align: center;
}
|
static
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/static/index.html
|
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<title>Hello, world</title>
<link rel="stylesheet" href="/style.css">
<script src="/script.js"></script>
</head>
<body>
<h1>Hello, world</h1>
<button onclick="fetchMessage()">Fetch Message</button>
<p id="message">Click on the button to fetch the message.</p>
</body>
</html>
|
static
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/appengine-hello/static/script.js
|
/*
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.
*/
"use strict";
function fetchMessage() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "/hello", false);
xmlHttp.send(null);
document.getElementById("message").innerHTML = xmlHttp.responseText;
}
|
slog-handler-guide
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/Makefile
|
all: README.md
go build ./...
README.md: guide.md ../internal/cmd/weave/*.go $(wildcard */*.go)
go run ../internal/cmd/weave guide.md >README.md
# This is for previewing using github.
# $HOME/markdown must be a github client.
test: README.md
cp README.md $$HOME/markdown/
(cd $$HOME/markdown/ && git commit -m . README.md && git push)
|
slog-handler-guide
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/README.md
|
<!-- Autogenerated by weave; DO NOT EDIT -->
# A Guide to Writing `slog` Handlers
This document is maintained by Jonathan Amsterdam `jba@google.com`.
# Contents
1. [Introduction](#introduction)
1. [Loggers and their handlers](#loggers-and-their-handlers)
1. [Implementing `Handler` methods](#implementing-`handler`-methods)
1. [The `Enabled` method](#the-`enabled`-method)
1. [The `Handle` method](#the-`handle`-method)
1. [The `WithAttrs` method](#the-`withattrs`-method)
1. [The `WithGroup` method](#the-`withgroup`-method)
1. [Testing](#testing)
1. [General considerations](#general-considerations)
1. [Copying records](#copying-records)
1. [Concurrency safety](#concurrency-safety)
1. [Robustness](#robustness)
1. [Speed](#speed)
# Introduction
The standard library’s `log/slog` package has a two-part design.
A "frontend," implemented by the `Logger` type,
gathers stuctured log information like a message, level, and attributes,
and passes them to a "backend," an implementation of the `Handler` interface.
The package comes with two built-in handlers that usually should be adequate.
But you may need to write your own handler, and that is not always straightforward.
This guide is here to help.
# Loggers and their handlers
Writing a handler requires an understanding of how the `Logger` and `Handler`
types work together.
Each logger contains a handler. Certain `Logger` methods do some preliminary work,
such as gathering key-value pairs into `Attr`s, and then call one or more
`Handler` methods. These `Logger` methods are `With`, `WithGroup`,
and the output methods.
An output method fulfills the main role of a logger: producing log output.
Here is a call to an output method:
logger.Info("hello", "key", value)
There are two general output methods, `Log`, and `LogAttrs`. For convenience,
there is an output method for each of four common levels (`Debug`, `Info`,
`Warn` and `Error`), and corresponding methods that take a context (`DebugContext`,
`InfoContext`, `WarnContext` and `ErrorContext`).
Each `Logger` output method first calls its handler's `Enabled` method. If that call
returns true, the method constructs a `Record` from its arguments and calls
the handler's `Handle` method.
As a convenience and an optimization, attributes can be added to
`Logger` by calling the `With` method:
logger = logger.With("k", v)
This call creates a new `Logger` value with the argument attributes; the
original remains unchanged.
All subsequent output from `logger` will include those attributes.
A logger's `With` method calls its handler's `WithAttrs` method.
The `WithGroup` method is used to avoid key collisions in large programs
by establishing separate namespaces.
This call creates a new `Logger` value with a group named "g":
logger = logger.WithGroup("g")
All subsequent keys for `logger` will be qualified by the group name "g".
Exactly what "qualified" means depends on how the logger's handler formats the
output.
The built-in `TextHandler` treats the group as a prefix to the key, separated by
a dot: `g.k` for a key `k`, for example.
The built-in `JSONHandler` uses the group as a key for a nested JSON object:
{"g": {"k": v}}
A logger's `WithGroup` method calls its handler's `WithGroup` method.
# Implementing `Handler` methods
We can now talk about the four `Handler` methods in detail.
Along the way, we will write a handler that formats logs using a format
reminsicent of YAML. It will display this log output call:
logger.Info("hello", "key", 23)
something like this:
time: 2023-05-15T16:29:00
level: INFO
message: "hello"
key: 23
---
Although this particular output is valid YAML,
our implementation doesn't consider the subtleties of YAML syntax,
so it will sometimes produce invalid YAML.
For example, it doesn't quote keys that have colons in them.
We'll call it `IndentHandler` to forestall disappointment.
We begin with the `IndentHandler` type
and the `New` function that constructs it from an `io.Writer` and options:
```
type IndentHandler struct {
opts Options
// TODO: state for WithGroup and WithAttrs
mu *sync.Mutex
out io.Writer
}
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
```
We'll support only one option, the ability to set a minimum level in order to
supress detailed log output.
Handlers should always declare this option to be a `slog.Leveler`.
The `slog.Leveler` interface is implemented by both `Level` and `LevelVar`.
A `Level` value is easy for the user to provide,
but changing the level of multiple handlers requires tracking them all.
If the user instead passes a `LevelVar`, then a single change to that `LevelVar`
will change the behavior of all handlers that contain it.
Changes to `LevelVar`s are goroutine-safe.
You might also consider adding a `ReplaceAttr` option to your handler,
like the [one for the built-in
handlers](https://pkg.go.dev/log/slog#HandlerOptions.ReplaceAttr).
Although `ReplaceAttr` will complicate your implementation, it will also
make your handler more generally useful.
The mutex will be used to ensure that writes to the `io.Writer` happen atomically.
Unusually, `IndentHandler` holds a pointer to a `sync.Mutex` rather than holding a
`sync.Mutex` directly.
There is a good reason for that, which we'll explain [later](#getting-the-mutex-right).
Our handler will need additional state to track calls to `WithGroup` and `WithAttrs`.
We will describe that state when we get to those methods.
## The `Enabled` method
The `Enabled` method is an optimization that can avoid unnecessary work.
A `Logger` output method will call `Enabled` before it processes any of its arguments,
to see if it should proceed.
The signature is
Enabled(context.Context, Level) bool
The context is available to allow decisions based on contextual information.
For example, a custom HTTP request header could specify a minimum level,
which the server adds to the context used for processing that request.
A handler's `Enabled` method could report whether the argument level
is greater than or equal to the context value, allowing the verbosity
of the work done by each request to be controlled independently.
Our `IndentHandler` doesn't use the context. It just compares the argument level
with its configured minimum level:
```
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
```
## The `Handle` method
The `Handle` method is passed a `Record` containing all the information to be
logged for a single call to a `Logger` output method.
The `Handle` method should deal with it in some way.
One way is to output the `Record` in some format, as `TextHandler` and `JSONHandler` do.
But other options are to modify the `Record` and pass it on to another handler,
enqueue the `Record` for later processing, or ignore it.
The signature of `Handle` is
Handle(context.Context, Record) error
The context is provided to support applications that provide logging information
along the call chain. In a break with usual Go practice, the `Handle` method
should not treat a canceled context as a signal to stop work.
If `Handle` processes its `Record`, it should follow the rules in the
[documentation](https://pkg.go.dev/log/slog#Handler.Handle).
For example, a zero `Time` field should be ignored, as should zero `Attr`s.
A `Handle` method that is going to produce output should carry out the following steps:
1. Allocate a buffer, typically a `[]byte`, to hold the output.
It's best to construct the output in memory first,
then write it with a single call to `io.Writer.Write`,
to minimize interleaving with other goroutines using the same writer.
2. Format the special fields: time, level, message, and source location (PC).
As a general rule, these fields should appear first and are not nested in
groups established by `WithGroup`.
3. Format the result of `WithGroup` and `WithAttrs` calls.
4. Format the attributes in the `Record`.
5. Output the buffer.
That is how `IndentHandler.Handle` is structured:
```
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
indentLevel := 0
// TODO: output the Attrs and groups from WithAttrs and WithGroup.
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, indentLevel)
return true
})
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
```
The first line allocates a `[]byte` that should be large enough for most log
output.
Allocating a buffer with some initial, fairly large capacity is a simple but
significant optimization: it avoids the repeated copying and allocation that
happen when the initial slice is empty or small.
We'll return to this line in the section on [speed](#speed)
and show how we can do even better.
The next part of our `Handle` method formats the special attributes,
observing the rules to ignore a zero time and a zero PC.
Next, the method processes the result of `WithAttrs` and `WithGroup` calls.
We'll skip that for now.
Then it's time to process the attributes in the argument record.
We use the `Record.Attrs` method to iterate over the attributes
in the order the user passed them to the `Logger` output method.
Handlers are free to reorder or de-duplicate the attributes,
but ours does not.
Lastly, after adding the line "---" to the output to separate log records,
our handler makes a single call to `h.out.Write` with the buffer we've accumulated.
We hold the lock for this write to make it atomic with respect to other
goroutines that may be calling `Handle` at the same time.
At the heart of the handler is the `appendAttr` method, responsible for
formatting a single attribute:
```
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
}
```
It begins by resolving the attribute, to run the `LogValuer.LogValue` method of
the value if it has one. All handlers should resolve every attribute they
process.
Next, it follows the handler rule that says that empty attributes should be
ignored.
Then it switches on the attribute kind to determine what format to use. For most
kinds (the default case of the switch), it relies on `slog.Value`'s `String` method to
produce something reasonable. It handles strings and times specially:
strings by quoting them, and times by formatting them in a standard way.
When `appendAttr` sees a `Group`, it calls itself recursively on the group's
attributes, after applying two more handler rules.
First, a group with no attributes is ignored—not even its key is displayed.
Second, a group with an empty key is inlined: the group boundary isn't marked in
any way. In our case, that means the group's attributes aren't indented.
## The `WithAttrs` method
One of `slog`'s performance optimizations is support for pre-formatting
attributes. The `Logger.With` method converts key-value pairs into `Attr`s and
then calls `Handler.WithAttrs`.
The handler may store the attributes for later consumption by the `Handle` method,
or it may take the opportunity to format the attributes now, once,
rather than doing so repeatedly on each call to `Handle`.
The signature of the `WithAttrs` method is
WithAttrs(attrs []Attr) Handler
The attributes are the processed key-value pairs passed to `Logger.With`.
The return value should be a new instance of your handler that contains
the attributes, possibly pre-formatted.
`WithAttrs` must return a new handler with the additional attributes, leaving
the original handler (its receiver) unchanged. For example, this call:
logger2 := logger1.With("k", v)
creates a new logger, `logger2`, with an additional attribute, but has no
effect on `logger1`.
We will show example implementations of `WithAttrs` below, when we discuss `WithGroup`.
## The `WithGroup` method
`Logger.WithGroup` calls `Handler.WithGroup` directly, with the same
argument, the group name.
A handler should remember the name so it can use it to qualify all subsequent
attributes.
The signature of `WithGroup` is:
WithGroup(name string) Handler
Like `WithAttrs`, the `WithGroup` method should return a new handler, not modify
the receiver.
The implementations of `WithGroup` and `WithAttrs` are intertwined.
Consider this statement:
logger = logger.WithGroup("g1").With("k1", 1).WithGroup("g2").With("k2", 2)
Subsequent `logger` output should qualify key "k1" with group "g1",
and key "k2" with groups "g1" and "g2".
The order of the `Logger.WithGroup` and `Logger.With` calls must be respected by
the implementations of `Handler.WithGroup` and `Handler.WithAttrs`.
We will look at two implementations of `WithGroup` and `WithAttrs`, one that pre-formats and
one that doesn't.
### Without pre-formatting
Our first implementation will collect the information from `WithGroup` and
`WithAttrs` calls to build up a slice of group names and attribute lists,
and loop over that slice in `Handle`. We start with a struct that can hold
either a group name or some attributes:
```
// groupOrAttrs holds either a group name or a list of slog.Attrs.
type groupOrAttrs struct {
group string // group name if non-empty
attrs []slog.Attr // attrs if non-empty
}
```
Then we add a slice of `groupOrAttrs` to our handler:
```
type IndentHandler struct {
opts Options
goas []groupOrAttrs
mu *sync.Mutex
out io.Writer
}
```
As stated above, The `WithGroup` and `WithAttrs` methods should not modify their
receiver.
To that end, we define a method that will copy our handler struct
and append one `groupOrAttrs` to the copy:
```
func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler {
h2 := *h
h2.goas = make([]groupOrAttrs, len(h.goas)+1)
copy(h2.goas, h.goas)
h2.goas[len(h2.goas)-1] = goa
return &h2
}
```
Most of the fields of `IndentHandler` can be copied shallowly, but the slice of
`groupOrAttrs` requires a deep copy, or the clone and the original will point to
the same underlying array. If we used `append` instead of making an explicit
copy, we would introduce that subtle aliasing bug.
Using `withGroupOrAttrs`, the `With` methods are easy:
```
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{group: name})
}
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})
}
```
The `Handle` method can now process the groupOrAttrs slice after
the built-in attributes and before the ones in the record:
```
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
indentLevel := 0
// Handle state from WithGroup and WithAttrs.
goas := h.goas
if r.NumAttrs() == 0 {
// If the record has no Attrs, remove groups at the end of the list; they are empty.
for len(goas) > 0 && goas[len(goas)-1].group != "" {
goas = goas[:len(goas)-1]
}
}
for _, goa := range goas {
if goa.group != "" {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", goa.group)
indentLevel++
} else {
for _, a := range goa.attrs {
buf = h.appendAttr(buf, a, indentLevel)
}
}
}
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, indentLevel)
return true
})
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
```
You may have noticed that our algorithm for
recording `WithGroup` and `WithAttrs` information is quadratic in the
number of calls to those methods, because of the repeated copying.
That is unlikely to matter in practice, but if it bothers you,
you can use a linked list instead,
which `Handle` will have to reverse or visit recursively.
See the
[github.com/jba/slog/withsupport](https://github.com/jba/slog/tree/main/withsupport)
package for an implementation.
#### Getting the mutex right
Let us revisit the last few lines of `Handle`:
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
This code hasn't changed, but we can now appreciate why `h.mu` is a
pointer to a `sync.Mutex`. Both `WithGroup` and `WithAttrs` copy the handler.
Both copies point to the same mutex.
If the copy and the original used different mutexes and were used concurrently,
then their output could be interleaved, or some output could be lost.
Code like this:
l2 := l1.With("a", 1)
go l1.Info("hello")
l2.Info("goodbye")
could produce output like this:
hegoollo a=dbye1
See [this bug report](https://go.dev/issue/61321) for more detail.
### With pre-formatting
Our second implementation implements pre-formatting.
This implementation is more complicated than the previous one.
Is the extra complexity worth it?
That depends on your circumstances, but here is one circumstance where
it might be.
Say that you wanted your server to log a lot of information about an incoming
request with every log message that happens during that request. A typical
handler might look something like this:
func (s *Server) handleWidgets(w http.ResponseWriter, r *http.Request) {
logger := s.logger.With(
"url", r.URL,
"traceID": r.Header.Get("X-Cloud-Trace-Context"),
// many other attributes
)
// ...
}
A single `handleWidgets` request might generate hundreds of log lines.
For instance, it might contain code like this:
for _, w := range widgets {
logger.Info("processing widget", "name", w.Name)
// ...
}
For every such line, the `Handle` method we wrote above will format all
the attributes that were added using `With` above, in addition to the
ones on the log line itself.
Maybe all that extra work doesn't slow down your server significantly, because
it does so much other work that time spent logging is just noise.
But perhaps your server is fast enough that all that extra formatting appears high up
in your CPU profiles. That is when pre-formatting can make a big difference,
by formatting the attributes in a call to `With` just once.
To pre-format the arguments to `WithAttrs`, we need to keep track of some
additional state in the `IndentHandler` struct.
```
type IndentHandler struct {
opts Options
preformatted []byte // data from WithGroup and WithAttrs
unopenedGroups []string // groups from WithGroup that haven't been opened
indentLevel int // same as number of opened groups so far
mu *sync.Mutex
out io.Writer
}
```
Mainly, we need a buffer to hold the pre-formatted data.
But we also need to keep track of which groups
we've seen but haven't output yet. We'll call those groups "unopened."
We also need to track how many groups we've opened, which we can do
with a simple counter, since an opened group's only effect is to change the
indentation level.
The `WithGroup` implementation is a lot like the previous one: just remember the
new group, which is unopened initially.
```
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
}
```
`WithAttrs` does all the pre-formatting:
```
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
}
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
}
```
It first opens any unopened groups. This handles calls like:
logger.WithGroup("g").WithGroup("h").With("a", 1)
Here, `WithAttrs` must output "g" and "h" before "a". Since a group established
by `WithGroup` is in effect for the rest of the log line, `WithAttrs` increments
the indentation level for each group it opens.
Lastly, `WithAttrs` formats its argument attributes, using the same `appendAttr`
method we saw above.
It's the `Handle` method's job to insert the pre-formatted material in the right
place, which is after the built-in attributes and before the ones in the record:
```
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
```
It must also open any groups that haven't yet been opened. The logic covers
log lines like this one:
logger.WithGroup("g").Info("msg", "a", 1)
where "g" is unopened before `Handle` is called and must be written to produce
the correct output:
level: INFO
msg: "msg"
g:
a: 1
The check for `r.NumAttrs() > 0` handles this case:
logger.WithGroup("g").Info("msg")
Here there are no record attributes, so no group to open.
## Testing
The [`Handler` contract](https://pkg.go.dev/log/slog#Handler) specifies several
constraints on handlers.
To verify that your handler follows these rules and generally produces proper
output, use the [testing/slogtest package](https://pkg.go.dev/testing/slogtest).
That package's `TestHandler` function takes an instance of your handler and
a function that returns its output formatted as a slice of maps. Here is the test function
for our example handler:
```
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
}
```
Calling `TestHandler` is easy. The hard part is parsing your handler's output.
`TestHandler` calls your handler multiple times, resulting in a sequence of log
entries.
It is your job to parse each entry into a `map[string]any`.
A group in an entry should appear as a nested map.
If your handler outputs a standard format, you can use an existing parser.
For example, if your handler outputs one JSON object per line, then you
can split the output into lines and call `encoding/json.Unmarshal` on each.
Parsers for other formats that can unmarshal into a map can be used out
of the box.
Our example output is enough like YAML so that we can use the `gopkg.in/yaml.v3`
package to parse it:
```
func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
```
If you have to write your own parser, it can be far from perfect.
The `slogtest` package uses only a handful of simple attributes.
(It is testing handler conformance, not parsing.)
Your parser can ignore edge cases like whitespace and newlines in keys and
values. Before switching to a YAML parser, we wrote an adequate custom parser
in 65 lines.
# General considerations
## Copying records
Most handlers won't need to copy the `slog.Record` that is passed
to the `Handle` method.
Those that do must take special care in some cases.
A handler can make a single copy of a `Record` with an ordinary Go
assignment, channel send or function call if it doesn't retain the
original.
But if its actions result in more than one copy, it should call `Record.Clone`
to make the copies so that they don't share state.
This `Handle` method passes the record to a single handler, so it doesn't require `Clone`:
type Handler1 struct {
h slog.Handler
// ...
}
func (h *Handler1) Handle(ctx context.Context, r slog.Record) error {
return h.h.Handle(ctx, r)
}
This `Handle` method might pass the record to more than one handler, so it
should use `Clone`:
type Handler2 struct {
hs []slog.Handler
// ...
}
func (h *Handler2) Handle(ctx context.Context, r slog.Record) error {
for _, hh := range h.hs {
if err := hh.Handle(ctx, r.Clone()); err != nil {
return err
}
}
return nil
}
## Concurrency safety
A handler must work properly when a single `Logger` is shared among several
goroutines.
That means that mutable state must be protected with a lock or some other mechanism.
In practice, this is not hard to achieve, because many handlers won't have any
mutable state.
- The `Enabled` method typically consults only its arguments and a configured
level. The level is often either set once initially, or is held in a
`LevelVar`, which is already concurrency-safe.
- The `WithAttrs` and `WithGroup` methods should not modify the receiver,
for reasons discussed above.
- The `Handle` method typically works only with its arguments and stored fields.
Calls to output methods like `io.Writer.Write` should be synchronized unless
it can be verified that no locking is needed.
As we saw in our example, storing a pointer to a mutex enables a logger and
all of its clones to synchronize with each other.
Beware of facile claims like "Unix writes are atomic"; the situation is a lot more nuanced than that.
Some handlers have legitimate reasons for keeping state.
For example, a handler might support a `SetLevel` method to change its configured level
dynamically.
Or it might output the time between sucessive calls to `Handle`,
which requires a mutable field holding the last output time.
Synchronize all accesses to such fields, both reads and writes.
The built-in handlers have no directly mutable state.
They use a mutex only to sequence calls to their contained `io.Writer`.
## Robustness
Logging is often the debugging technique of last resort. When it is difficult or
impossible to inspect a system, as is typically the case with a production
server, logs provide the most detailed way to understand its behavior.
Therefore, your handler should be robust to bad input.
For example, the usual advice when when a function discovers a problem,
like an invalid argument, is to panic or return an error.
The built-in handlers do not follow that advice.
Few things are more frustrating than being unable to debug a problem that
causes logging to fail;
it is better to produce some output, however imperfect, than to produce none at all.
That is why methods like `Logger.Info` convert programming bugs in their list of
key-value pairs, like missing values or malformed keys,
into `Attr`s that contain as much information as possible.
One place to avoid panics is in processing attribute values. A handler that wants
to format a value will probably switch on the value's kind:
switch attr.Value.Kind() {
case KindString: ...
case KindTime: ...
// all other Kinds
default: ...
}
What should happen in the default case, when the handler encounters a `Kind`
that it doesn't know about?
The built-in handlers try to muddle through by using the result of the value's
`String` method, as our example handler does.
They do not panic or return an error.
Your own handlers might in addition want to report the problem through your production monitoring
or error-tracking telemetry system.
The most likely explanation for the issue is that a newer version of the `slog` package added
a new `Kind`—a backwards-compatible change under the Go 1 Compatibility
Promise—and the handler wasn't updated.
That is certainly a problem, but it shouldn't deprive
readers from seeing the rest of the log output.
There is one circumstance where returning an error from `Handler.Handle` is appropriate.
If the output operation itself fails, the best course of action is to report
this failure by returning the error. For instance, the last two lines of the
built-in `Handle` methods are
_, err := h.w.Write(*state.buf)
return err
Although the output methods of `Logger` ignore the error, one could write a
handler that does something with it, perhaps falling back to writing to standard
error.
## Speed
Most programs don't need fast logging.
Before making your handler fast, gather data—preferably production data,
not benchmark comparisons—that demonstrates that it needs to be fast.
Avoid premature optimization.
If you need a fast handler, start with pre-formatting. It may provide dramatic
speed-ups in cases where a single call to `Logger.With` is followed by many
calls to the resulting logger.
If log output is the bottleneck, consider making your handler asynchronous.
Do the minimal amount of processing in the handler, then send the record and
other information over a channel. Another goroutine can collect the incoming log
entries and write them in bulk and in the background.
You might want to preserve the option to log synchronously
so you can see all the log output to debug a crash.
Allocation is often a major cause of a slow system.
The `slog` package already works hard at minimizing allocations.
If your handler does its own allocation, and profiling shows it to be
a problem, then see if you can minimize it.
One simple change you can make is to replace calls to `fmt.Sprintf` or `fmt.Appendf`
with direct appends to the buffer. For example, our IndentHandler appends string
attributes to the buffer like so:
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
As of Go 1.21, that results in two allocations, one for each argument passed to
an `any` parameter. We can get that down to zero by using `append` directly:
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
Another worthwhile change is to use a `sync.Pool` to manage the one chunk of
memory that most handlers need:
the `[]byte` buffer holding the formatted output.
Our example `Handle` method began with this line:
buf := make([]byte, 0, 1024)
As we said above, providing a large initial capacity avoids repeated copying and
re-allocation of the slice as it grows, reducing the number of allocations to
one.
But we can get it down to zero in the steady state by keeping a global pool of buffers.
Initially, the pool will be empty and new buffers will be allocated.
But eventually, assuming the number of concurrent log calls reaches a steady
maximum, there will be enough buffers in the pool to share among all the
ongoing `Handler` calls. As long as no log entry grows past a buffer's capacity,
there will be no allocations from the garbage collector's point of view.
We will hide our pool behind a pair of functions, `allocBuf` and `freeBuf`.
The single line to get a buffer at the top of `Handle` becomes two lines:
bufp := allocBuf()
defer freeBuf(bufp)
One of the subtleties involved in making a `sync.Pool` of slices
is suggested by the variable name `bufp`: your pool must deal in
_pointers_ to slices, not the slices themselves.
Pooled values must always be pointers. If they aren't, then the `any` arguments
and return values of the `sync.Pool` methods will themselves cause allocations,
defeating the purpose of pooling.
There are two ways to proceed with our slice pointer: we can replace `buf`
with `*bufp` throughout our function, or we can dereference it and remember to
re-assign it before freeing:
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()
Here is our pool and its associated functions:
```
var bufPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 1024)
return &b
},
}
func allocBuf() *[]byte {
return bufPool.Get().(*[]byte)
}
func freeBuf(b *[]byte) {
// To reduce peak allocation, return only smaller buffers to the pool.
const maxBufferSize = 16 << 10
if cap(*b) <= maxBufferSize {
*b = (*b)[:0]
bufPool.Put(b)
}
}
```
The pool's `New` function does the same thing as the original code:
create a byte slice with 0 length and plenty of capacity.
The `allocBuf` function just type-asserts the result of the pool's
`Get` method.
The `freeBuf` method truncates the buffer before putting it back
in the pool, so that `allocBuf` always returns zero-length slices.
It also implements an important optimization: it doesn't return
large buffers to the pool.
To see why this important, consider what would happen if there were a single,
unusually large log entry—say one that was a megabyte when formatted.
If that megabyte-sized buffer were put in the pool, it could remain
there indefinitely, constantly being reused, but with most of its capacity
wasted.
The extra memory might never be used again by the handler, and since it was in
the handler's pool, it might never be garbage-collected for reuse elsewhere.
We can avoid that situation by excluding large buffers from the pool.
|
slog-handler-guide
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/guide.md
|
# A Guide to Writing `slog` Handlers
This document is maintained by Jonathan Amsterdam `jba@google.com`.
# Contents
%toc
# Introduction
The standard library’s `log/slog` package has a two-part design.
A "frontend," implemented by the `Logger` type,
gathers stuctured log information like a message, level, and attributes,
and passes them to a "backend," an implementation of the `Handler` interface.
The package comes with two built-in handlers that usually should be adequate.
But you may need to write your own handler, and that is not always straightforward.
This guide is here to help.
# Loggers and their handlers
Writing a handler requires an understanding of how the `Logger` and `Handler`
types work together.
Each logger contains a handler. Certain `Logger` methods do some preliminary work,
such as gathering key-value pairs into `Attr`s, and then call one or more
`Handler` methods. These `Logger` methods are `With`, `WithGroup`,
and the output methods.
An output method fulfills the main role of a logger: producing log output.
Here is a call to an output method:
logger.Info("hello", "key", value)
There are two general output methods, `Log`, and `LogAttrs`. For convenience,
there is an output method for each of four common levels (`Debug`, `Info`,
`Warn` and `Error`), and corresponding methods that take a context (`DebugContext`,
`InfoContext`, `WarnContext` and `ErrorContext`).
Each `Logger` output method first calls its handler's `Enabled` method. If that call
returns true, the method constructs a `Record` from its arguments and calls
the handler's `Handle` method.
As a convenience and an optimization, attributes can be added to
`Logger` by calling the `With` method:
logger = logger.With("k", v)
This call creates a new `Logger` value with the argument attributes; the
original remains unchanged.
All subsequent output from `logger` will include those attributes.
A logger's `With` method calls its handler's `WithAttrs` method.
The `WithGroup` method is used to avoid avoid key collisions in large programs
by establishing separate namespaces.
This call creates a new `Logger` value with a group named "g":
logger = logger.WithGroup("g")
All subsequent keys for `logger` will be qualified by the group name "g".
Exactly what "qualified" means depends on how the logger's handler formats the
output.
The built-in `TextHandler` treats the group as a prefix to the key, separated by
a dot: `g.k` for a key `k`, for example.
The built-in `JSONHandler` uses the group as a key for a nested JSON object:
{"g": {"k": v}}
A logger's `WithGroup` method calls its handler's `WithGroup` method.
# Implementing `Handler` methods
We can now talk about the four `Handler` methods in detail.
Along the way, we will write a handler that formats logs using a format
reminsicent of YAML. It will display this log output call:
logger.Info("hello", "key", 23)
something like this:
time: 2023-05-15T16:29:00
level: INFO
message: "hello"
key: 23
---
Although this particular output is valid YAML,
our implementation doesn't consider the subtleties of YAML syntax,
so it will sometimes produce invalid YAML.
For example, it doesn't quote keys that have colons in them.
We'll call it `IndentHandler` to forestall disappointment.
We begin with the `IndentHandler` type
and the `New` function that constructs it from an `io.Writer` and options:
%include indenthandler1/indent_handler.go types -
We'll support only one option, the ability to set a minimum level in order to
supress detailed log output.
Handlers should always declare this option to be a `slog.Leveler`.
The `slog.Leveler` interface is implemented by both `Level` and `LevelVar`.
A `Level` value is easy for the user to provide,
but changing the level of multiple handlers requires tracking them all.
If the user instead passes a `LevelVar`, then a single change to that `LevelVar`
will change the behavior of all handlers that contain it.
Changes to `LevelVar`s are goroutine-safe.
You might also consider adding a `ReplaceAttr` option to your handler,
like the [one for the built-in
handlers](https://pkg.go.dev/log/slog#HandlerOptions.ReplaceAttr).
Although `ReplaceAttr` will complicate your implementation, it will also
make your handler more generally useful.
The mutex will be used to ensure that writes to the `io.Writer` happen atomically.
Unusually, `IndentHandler` holds a pointer to a `sync.Mutex` rather than holding a
`sync.Mutex` directly.
There is a good reason for that, which we'll explain [later](#getting-the-mutex-right).
Our handler will need additional state to track calls to `WithGroup` and `WithAttrs`.
We will describe that state when we get to those methods.
## The `Enabled` method
The `Enabled` method is an optimization that can avoid unnecessary work.
A `Logger` output method will call `Enabled` before it processes any of its arguments,
to see if it should proceed.
The signature is
Enabled(context.Context, Level) bool
The context is available to allow decisions based on contextual information.
For example, a custom HTTP request header could specify a minimum level,
which the server adds to the context used for processing that request.
A handler's `Enabled` method could report whether the argument level
is greater than or equal to the context value, allowing the verbosity
of the work done by each request to be controlled independently.
Our `IndentHandler` doesn't use the context. It just compares the argument level
with its configured minimum level:
%include indenthandler1/indent_handler.go enabled -
## The `Handle` method
The `Handle` method is passed a `Record` containing all the information to be
logged for a single call to a `Logger` output method.
The `Handle` method should deal with it in some way.
One way is to output the `Record` in some format, as `TextHandler` and `JSONHandler` do.
But other options are to modify the `Record` and pass it on to another handler,
enqueue the `Record` for later processing, or ignore it.
The signature of `Handle` is
Handle(context.Context, Record) error
The context is provided to support applications that provide logging information
along the call chain. In a break with usual Go practice, the `Handle` method
should not treat a canceled context as a signal to stop work.
If `Handle` processes its `Record`, it should follow the rules in the
[documentation](https://pkg.go.dev/log/slog#Handler.Handle).
For example, a zero `Time` field should be ignored, as should zero `Attr`s.
A `Handle` method that is going to produce output should carry out the following steps:
1. Allocate a buffer, typically a `[]byte`, to hold the output.
It's best to construct the output in memory first,
then write it with a single call to `io.Writer.Write`,
to minimize interleaving with other goroutines using the same writer.
2. Format the special fields: time, level, message, and source location (PC).
As a general rule, these fields should appear first and are not nested in
groups established by `WithGroup`.
3. Format the result of `WithGroup` and `WithAttrs` calls.
4. Format the attributes in the `Record`.
5. Output the buffer.
That is how `IndentHandler.Handle` is structured:
%include indenthandler1/indent_handler.go handle -
The first line allocates a `[]byte` that should be large enough for most log
output.
Allocating a buffer with some initial, fairly large capacity is a simple but
significant optimization: it avoids the repeated copying and allocation that
happen when the initial slice is empty or small.
We'll return to this line in the section on [speed](#speed)
and show how we can do even better.
The next part of our `Handle` method formats the special attributes,
observing the rules to ignore a zero time and a zero PC.
Next, the method processes the result of `WithAttrs` and `WithGroup` calls.
We'll skip that for now.
Then it's time to process the attributes in the argument record.
We use the `Record.Attrs` method to iterate over the attributes
in the order the user passed them to the `Logger` output method.
Handlers are free to reorder or de-duplicate the attributes,
but ours does not.
Lastly, after adding the line "---" to the output to separate log records,
our handler makes a single call to `h.out.Write` with the buffer we've accumulated.
We hold the lock for this write to make it atomic with respect to other
goroutines that may be calling `Handle` at the same time.
At the heart of the handler is the `appendAttr` method, responsible for
formatting a single attribute:
%include indenthandler1/indent_handler.go appendAttr -
It begins by resolving the attribute, to run the `LogValuer.LogValue` method of
the value if it has one. All handlers should resolve every attribute they
process.
Next, it follows the handler rule that says that empty attributes should be
ignored.
Then it switches on the attribute kind to determine what format to use. For most
kinds (the default case of the switch), it relies on `slog.Value`'s `String` method to
produce something reasonable. It handles strings and times specially:
strings by quoting them, and times by formatting them in a standard way.
When `appendAttr` sees a `Group`, it calls itself recursively on the group's
attributes, after applying two more handler rules.
First, a group with no attributes is ignored—not even its key is displayed.
Second, a group with an empty key is inlined: the group boundary isn't marked in
any way. In our case, that means the group's attributes aren't indented.
## The `WithAttrs` method
One of `slog`'s performance optimizations is support for pre-formatting
attributes. The `Logger.With` method converts key-value pairs into `Attr`s and
then calls `Handler.WithAttrs`.
The handler may store the attributes for later consumption by the `Handle` method,
or it may take the opportunity to format the attributes now, once,
rather than doing so repeatedly on each call to `Handle`.
The signature of the `WithAttrs` method is
WithAttrs(attrs []Attr) Handler
The attributes are the processed key-value pairs passed to `Logger.With`.
The return value should be a new instance of your handler that contains
the attributes, possibly pre-formatted.
`WithAttrs` must return a new handler with the additional attributes, leaving
the original handler (its receiver) unchanged. For example, this call:
logger2 := logger1.With("k", v)
creates a new logger, `logger2`, with an additional attribute, but has no
effect on `logger1`.
We will show example implementations of `WithAttrs` below, when we discuss `WithGroup`.
## The `WithGroup` method
`Logger.WithGroup` calls `Handler.WithGroup` directly, with the same
argument, the group name.
A handler should remember the name so it can use it to qualify all subsequent
attributes.
The signature of `WithGroup` is:
WithGroup(name string) Handler
Like `WithAttrs`, the `WithGroup` method should return a new handler, not modify
the receiver.
The implementations of `WithGroup` and `WithAttrs` are intertwined.
Consider this statement:
logger = logger.WithGroup("g1").With("k1", 1).WithGroup("g2").With("k2", 2)
Subsequent `logger` output should qualify key "k1" with group "g1",
and key "k2" with groups "g1" and "g2".
The order of the `Logger.WithGroup` and `Logger.With` calls must be respected by
the implementations of `Handler.WithGroup` and `Handler.WithAttrs`.
We will look at two implementations of `WithGroup` and `WithAttrs`, one that pre-formats and
one that doesn't.
### Without pre-formatting
Our first implementation will collect the information from `WithGroup` and
`WithAttrs` calls to build up a slice of group names and attribute lists,
and loop over that slice in `Handle`. We start with a struct that can hold
either a group name or some attributes:
%include indenthandler2/indent_handler.go gora -
Then we add a slice of `groupOrAttrs` to our handler:
%include indenthandler2/indent_handler.go IndentHandler -
As stated above, The `WithGroup` and `WithAttrs` methods should not modify their
receiver.
To that end, we define a method that will copy our handler struct
and append one `groupOrAttrs` to the copy:
%include indenthandler2/indent_handler.go withgora -
Most of the fields of `IndentHandler` can be copied shallowly, but the slice of
`groupOrAttrs` requires a deep copy, or the clone and the original will point to
the same underlying array. If we used `append` instead of making an explicit
copy, we would introduce that subtle aliasing bug.
Using `withGroupOrAttrs`, the `With` methods are easy:
%include indenthandler2/indent_handler.go withs -
The `Handle` method can now process the groupOrAttrs slice after
the built-in attributes and before the ones in the record:
%include indenthandler2/indent_handler.go handle -
You may have noticed that our algorithm for
recording `WithGroup` and `WithAttrs` information is quadratic in the
number of calls to those methods, because of the repeated copying.
That is unlikely to matter in practice, but if it bothers you,
you can use a linked list instead,
which `Handle` will have to reverse or visit recursively.
See the
[github.com/jba/slog/withsupport](https://github.com/jba/slog/tree/main/withsupport)
package for an implementation.
#### Getting the mutex right
Let us revisit the last few lines of `Handle`:
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
This code hasn't changed, but we can now appreciate why `h.mu` is a
pointer to a `sync.Mutex`. Both `WithGroup` and `WithAttrs` copy the handler.
Both copies point to the same mutex.
If the copy and the original used different mutexes and were used concurrently,
then their output could be interleaved, or some output could be lost.
Code like this:
l2 := l1.With("a", 1)
go l1.Info("hello")
l2.Info("goodbye")
could produce output like this:
hegoollo a=dbye1
See [this bug report](https://go.dev/issue/61321) for more detail.
### With pre-formatting
Our second implementation implements pre-formatting.
This implementation is more complicated than the previous one.
Is the extra complexity worth it?
That depends on your circumstances, but here is one circumstance where
it might be.
Say that you wanted your server to log a lot of information about an incoming
request with every log message that happens during that request. A typical
handler might look something like this:
func (s *Server) handleWidgets(w http.ResponseWriter, r *http.Request) {
logger := s.logger.With(
"url", r.URL,
"traceID": r.Header.Get("X-Cloud-Trace-Context"),
// many other attributes
)
// ...
}
A single `handleWidgets` request might generate hundreds of log lines.
For instance, it might contain code like this:
for _, w := range widgets {
logger.Info("processing widget", "name", w.Name)
// ...
}
For every such line, the `Handle` method we wrote above will format all
the attributes that were added using `With` above, in addition to the
ones on the log line itself.
Maybe all that extra work doesn't slow down your server significantly, because
it does so much other work that time spent logging is just noise.
But perhaps your server is fast enough that all that extra formatting appears high up
in your CPU profiles. That is when pre-formatting can make a big difference,
by formatting the attributes in a call to `With` just once.
To pre-format the arguments to `WithAttrs`, we need to keep track of some
additional state in the `IndentHandler` struct.
%include indenthandler3/indent_handler.go IndentHandler -
Mainly, we need a buffer to hold the pre-formatted data.
But we also need to keep track of which groups
we've seen but haven't output yet. We'll call those groups "unopened."
We also need to track how many groups we've opened, which we can do
with a simple counter, since an opened group's only effect is to change the
indentation level.
The `WithGroup` implementation is a lot like the previous one: just remember the
new group, which is unopened initially.
%include indenthandler3/indent_handler.go WithGroup -
`WithAttrs` does all the pre-formatting:
%include indenthandler3/indent_handler.go WithAttrs -
It first opens any unopened groups. This handles calls like:
logger.WithGroup("g").WithGroup("h").With("a", 1)
Here, `WithAttrs` must output "g" and "h" before "a". Since a group established
by `WithGroup` is in effect for the rest of the log line, `WithAttrs` increments
the indentation level for each group it opens.
Lastly, `WithAttrs` formats its argument attributes, using the same `appendAttr`
method we saw above.
It's the `Handle` method's job to insert the pre-formatted material in the right
place, which is after the built-in attributes and before the ones in the record:
%include indenthandler3/indent_handler.go Handle -
It must also open any groups that haven't yet been opened. The logic covers
log lines like this one:
logger.WithGroup("g").Info("msg", "a", 1)
where "g" is unopened before `Handle` is called and must be written to produce
the correct output:
level: INFO
msg: "msg"
g:
a: 1
The check for `r.NumAttrs() > 0` handles this case:
logger.WithGroup("g").Info("msg")
Here there are no record attributes, so no group to open.
## Testing
The [`Handler` contract](https://pkg.go.dev/log/slog#Handler) specifies several
constraints on handlers.
To verify that your handler follows these rules and generally produces proper
output, use the [testing/slogtest package](https://pkg.go.dev/testing/slogtest).
That package's `TestHandler` function takes an instance of your handler and
a function that returns its output formatted as a slice of maps. Here is the test function
for our example handler:
%include indenthandler3/indent_handler_test.go TestSlogtest -
Calling `TestHandler` is easy. The hard part is parsing your handler's output.
`TestHandler` calls your handler multiple times, resulting in a sequence of log
entries.
It is your job to parse each entry into a `map[string]any`.
A group in an entry should appear as a nested map.
If your handler outputs a standard format, you can use an existing parser.
For example, if your handler outputs one JSON object per line, then you
can split the output into lines and call `encoding/json.Unmarshal` on each.
Parsers for other formats that can unmarshal into a map can be used out
of the box.
Our example output is enough like YAML so that we can use the `gopkg.in/yaml.v3`
package to parse it:
%include indenthandler3/indent_handler_test.go parseLogEntries -
If you have to write your own parser, it can be far from perfect.
The `slogtest` package uses only a handful of simple attributes.
(It is testing handler conformance, not parsing.)
Your parser can ignore edge cases like whitespace and newlines in keys and
values. Before switching to a YAML parser, we wrote an adequate custom parser
in 65 lines.
# General considerations
## Copying records
Most handlers won't need to copy the `slog.Record` that is passed
to the `Handle` method.
Those that do must take special care in some cases.
A handler can make a single copy of a `Record` with an ordinary Go
assignment, channel send or function call if it doesn't retain the
original.
But if its actions result in more than one copy, it should call `Record.Clone`
to make the copies so that they don't share state.
This `Handle` method passes the record to a single handler, so it doesn't require `Clone`:
type Handler1 struct {
h slog.Handler
// ...
}
func (h *Handler1) Handle(ctx context.Context, r slog.Record) error {
return h.h.Handle(ctx, r)
}
This `Handle` method might pass the record to more than one handler, so it
should use `Clone`:
type Handler2 struct {
hs []slog.Handler
// ...
}
func (h *Handler2) Handle(ctx context.Context, r slog.Record) error {
for _, hh := range h.hs {
if err := hh.Handle(ctx, r.Clone()); err != nil {
return err
}
}
return nil
}
## Concurrency safety
A handler must work properly when a single `Logger` is shared among several
goroutines.
That means that mutable state must be protected with a lock or some other mechanism.
In practice, this is not hard to achieve, because many handlers won't have any
mutable state.
- The `Enabled` method typically consults only its arguments and a configured
level. The level is often either set once initially, or is held in a
`LevelVar`, which is already concurrency-safe.
- The `WithAttrs` and `WithGroup` methods should not modify the receiver,
for reasons discussed above.
- The `Handle` method typically works only with its arguments and stored fields.
Calls to output methods like `io.Writer.Write` should be synchronized unless
it can be verified that no locking is needed.
As we saw in our example, storing a pointer to a mutex enables a logger and
all of its clones to synchronize with each other.
Beware of facile claims like "Unix writes are atomic"; the situation is a lot more nuanced than that.
Some handlers have legitimate reasons for keeping state.
For example, a handler might support a `SetLevel` method to change its configured level
dynamically.
Or it might output the time between sucessive calls to `Handle`,
which requires a mutable field holding the last output time.
Synchronize all accesses to such fields, both reads and writes.
The built-in handlers have no directly mutable state.
They use a mutex only to sequence calls to their contained `io.Writer`.
## Robustness
Logging is often the debugging technique of last resort. When it is difficult or
impossible to inspect a system, as is typically the case with a production
server, logs provide the most detailed way to understand its behavior.
Therefore, your handler should be robust to bad input.
For example, the usual advice when when a function discovers a problem,
like an invalid argument, is to panic or return an error.
The built-in handlers do not follow that advice.
Few things are more frustrating than being unable to debug a problem that
causes logging to fail;
it is better to produce some output, however imperfect, than to produce none at all.
That is why methods like `Logger.Info` convert programming bugs in their list of
key-value pairs, like missing values or malformed keys,
into `Attr`s that contain as much information as possible.
One place to avoid panics is in processing attribute values. A handler that wants
to format a value will probably switch on the value's kind:
switch attr.Value.Kind() {
case KindString: ...
case KindTime: ...
// all other Kinds
default: ...
}
What should happen in the default case, when the handler encounters a `Kind`
that it doesn't know about?
The built-in handlers try to muddle through by using the result of the value's
`String` method, as our example handler does.
They do not panic or return an error.
Your own handlers might in addition want to report the problem through your production monitoring
or error-tracking telemetry system.
The most likely explanation for the issue is that a newer version of the `slog` package added
a new `Kind`—a backwards-compatible change under the Go 1 Compatibility
Promise—and the handler wasn't updated.
That is certainly a problem, but it shouldn't deprive
readers from seeing the rest of the log output.
There is one circumstance where returning an error from `Handler.Handle` is appropriate.
If the output operation itself fails, the best course of action is to report
this failure by returning the error. For instance, the last two lines of the
built-in `Handle` methods are
_, err := h.w.Write(*state.buf)
return err
Although the output methods of `Logger` ignore the error, one could write a
handler that does something with it, perhaps falling back to writing to standard
error.
## Speed
Most programs don't need fast logging.
Before making your handler fast, gather data—preferably production data,
not benchmark comparisons—that demonstrates that it needs to be fast.
Avoid premature optimization.
If you need a fast handler, start with pre-formatting. It may provide dramatic
speed-ups in cases where a single call to `Logger.With` is followed by many
calls to the resulting logger.
If log output is the bottleneck, consider making your handler asynchronous.
Do the minimal amount of processing in the handler, then send the record and
other information over a channel. Another goroutine can collect the incoming log
entries and write them in bulk and in the background.
You might want to preserve the option to log synchronously
so you can see all the log output to debug a crash.
Allocation is often a major cause of a slow system.
The `slog` package already works hard at minimizing allocations.
If your handler does its own allocation, and profiling shows it to be
a problem, then see if you can minimize it.
One simple change you can make is to replace calls to `fmt.Sprintf` or `fmt.Appendf`
with direct appends to the buffer. For example, our IndentHandler appends string
attributes to the buffer like so:
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
As of Go 1.21, that results in two allocations, one for each argument passed to
an `any` parameter. We can get that down to zero by using `append` directly:
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
Another worthwhile change is to use a `sync.Pool` to manage the one chunk of
memory that most handlers need:
the `[]byte` buffer holding the formatted output.
Our example `Handle` method began with this line:
buf := make([]byte, 0, 1024)
As we said above, providing a large initial capacity avoids repeated copying and
re-allocation of the slice as it grows, reducing the number of allocations to
one.
But we can get it down to zero in the steady state by keeping a global pool of buffers.
Initially, the pool will be empty and new buffers will be allocated.
But eventually, assuming the number of concurrent log calls reaches a steady
maximum, there will be enough buffers in the pool to share among all the
ongoing `Handler` calls. As long as no log entry grows past a buffer's capacity,
there will be no allocations from the garbage collector's point of view.
We will hide our pool behind a pair of functions, `allocBuf` and `freeBuf`.
The single line to get a buffer at the top of `Handle` becomes two lines:
bufp := allocBuf()
defer freeBuf(bufp)
One of the subtleties involved in making a `sync.Pool` of slices
is suggested by the variable name `bufp`: your pool must deal in
_pointers_ to slices, not the slices themselves.
Pooled values must always be pointers. If they aren't, then the `any` arguments
and return values of the `sync.Pool` methods will themselves cause allocations,
defeating the purpose of pooling.
There are two ways to proceed with our slice pointer: we can replace `buf`
with `*bufp` throughout our function, or we can dereference it and remember to
re-assign it before freeing:
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()
Here is our pool and its associated functions:
%include indenthandler4/indent_handler.go pool -
The pool's `New` function does the same thing as the original code:
create a byte slice with 0 length and plenty of capacity.
The `allocBuf` function just type-asserts the result of the pool's
`Get` method.
The `freeBuf` method truncates the buffer before putting it back
in the pool, so that `allocBuf` always returns zero-length slices.
It also implements an important optimization: it doesn't return
large buffers to the pool.
To see why this important, consider what would happen if there were a single,
unusually large log entry—say one that was a megabyte when formatted.
If that megabyte-sized buffer were put in the pool, it could remain
there indefinitely, constantly being reused, but with most of its capacity
wasted.
The extra memory might never be used again by the handler, and since it was in
the handler's pool, it might never be garbage-collected for reuse elsewhere.
We can avoid that situation by excluding large buffers from the pool.
|
indenthandler2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
|
//go:build go1.21
package indenthandler
import (
"bufio"
"bytes"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"unicode"
"log/slog"
"testing/slogtest"
)
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(buf.String())
})
if err != nil {
t.Error(err)
}
}
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
func parseLogEntries(s string) []map[string]any {
var ms []map[string]any
scan := bufio.NewScanner(strings.NewReader(s))
for scan.Scan() {
m := parseGroup(scan)
ms = append(ms, m)
}
if scan.Err() != nil {
panic(scan.Err())
}
return ms
}
func parseGroup(scan *bufio.Scanner) map[string]any {
m := map[string]any{}
groupIndent := -1
for {
line := scan.Text()
if line == "---" { // end of entry
break
}
k, v, found := strings.Cut(line, ":")
if !found {
panic(fmt.Sprintf("no ':' in line %q", line))
}
indent := strings.IndexFunc(k, func(r rune) bool {
return !unicode.IsSpace(r)
})
if indent < 0 {
panic("blank line")
}
if groupIndent < 0 {
// First line in group; remember the indent.
groupIndent = indent
} else if indent < groupIndent {
// End of group
break
} else if indent > groupIndent {
panic(fmt.Sprintf("indent increased on line %q", line))
}
key := strings.TrimSpace(k)
if v == "" {
// Just a key: start of a group.
if !scan.Scan() {
panic("empty group")
}
m[key] = parseGroup(scan)
} else {
v = strings.TrimSpace(v)
if len(v) > 0 && v[0] == '"' {
var err error
v, err = strconv.Unquote(v)
if err != nil {
panic(err)
}
}
m[key] = v
if !scan.Scan() {
break
}
}
}
return m
}
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: 5
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": "1",
"b": "2",
"c": "3",
"g": map[string]any{
"h": "4",
"i": "5",
},
"d": "6",
},
{
"e": "7",
},
}
got := parseLogEntries(in[1:])
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
|
indenthandler2
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler2/indent_handler.go
|
//go:build go1.21
package indenthandler
import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"sync"
"time"
)
// !+IndentHandler
type IndentHandler struct {
opts Options
goas []groupOrAttrs
mu *sync.Mutex
out io.Writer
}
//!-IndentHandler
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
// !+gora
// groupOrAttrs holds either a group name or a list of slog.Attrs.
type groupOrAttrs struct {
group string // group name if non-empty
attrs []slog.Attr // attrs if non-empty
}
//!-gora
func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
// !+withs
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{group: name})
}
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})
}
//!-withs
// !+withgora
func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler {
h2 := *h
h2.goas = make([]groupOrAttrs, len(h.goas)+1)
copy(h2.goas, h.goas)
h2.goas[len(h2.goas)-1] = goa
return &h2
}
//!-withgora
// !+handle
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
indentLevel := 0
// Handle state from WithGroup and WithAttrs.
goas := h.goas
if r.NumAttrs() == 0 {
// If the record has no Attrs, remove groups at the end of the list; they are empty.
for len(goas) > 0 && goas[len(goas)-1].group != "" {
goas = goas[:len(goas)-1]
}
}
for _, goa := range goas {
if goa.group != "" {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", goa.group)
indentLevel++
} else {
for _, a := range goa.attrs {
buf = h.appendAttr(buf, a, indentLevel)
}
}
}
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, indentLevel)
return true
})
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
//!-handle
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
}
|
indenthandler3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go
|
//go:build go1.21
package indenthandler
import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
)
// !+TestSlogtest
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
}
// !-TestSlogtest
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
// !+parseLogEntries
func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
// !-parseLogEntries
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
|
indenthandler3
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler3/indent_handler.go
|
//go:build go1.21
package indenthandler
import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"slices"
"sync"
"time"
)
// !+IndentHandler
type IndentHandler struct {
opts Options
preformatted []byte // data from WithGroup and WithAttrs
unopenedGroups []string // groups from WithGroup that haven't been opened
indentLevel int // same as number of opened groups so far
mu *sync.Mutex
out io.Writer
}
//!-IndentHandler
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
// !+WithGroup
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
}
//!-WithGroup
// !+WithAttrs
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
}
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
}
//!-WithAttrs
// !+Handle
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
//!-Handle
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
}
|
indenthandler4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go
|
//go:build go1.21
package indenthandler
import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
)
// !+TestSlogtest
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
}
// !-TestSlogtest
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
// !+parseLogEntries
func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
// !-parseLogEntries
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
|
indenthandler4
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/example/slog-handler-guide/indenthandler4/indent_handler_norace_test.go
|
//go:build go1.21 && !race
package indenthandler
import (
"fmt"
"io"
"log/slog"
"strconv"
"testing"
)
func TestAlloc(t *testing.T) {
a := slog.String("key", "value")
t.Run("Appendf", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
})
if g, w := int(g), 2; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("appends", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
})
if g, w := int(g), 0; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("Handle", func(t *testing.T) {
l := slog.New(New(io.Discard, nil))
got := testing.AllocsPerRun(10, func() {
l.LogAttrs(nil, slog.LevelInfo, "hello", slog.String("a", "1"))
})
if g, w := int(got), 6; g > w {
t.Errorf("got %d, want at most %d", g, w)
}
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.