### Install go-check-sumtype Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Use 'go get' to install the go-check-sumtype utility. ```go go get github.com/alecthomas/go-check-sumtype ``` -------------------------------- ### Install and Run go-check-sumtype CLI Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt Install the tool using 'go get' and run it against Go packages or files. It accepts standard Go package patterns. ```bash go get github.com/alecthomas/go-check-sumtype ``` ```bash # Check all packages in the current module (excluding vendor) go list ./... | grep -v vendor | xargs go-check-sumtype ``` ```bash # Check a single package go-check-sumtype ./mypkg ``` ```bash # Check a specific file go-check-sumtype myfile.go ``` ```bash # Disable default-clause bypass (default is true; set false to enforce strict exhaustiveness) go-check-sumtype -default-signifies-exhaustive=false $(go list ./...) ``` ```bash # Include shared interfaces in exhaustiveness checking go-check-sumtype -include-shared-interfaces=true $(go list ./...) ``` ```bash # Show debug output go-check-sumtype -debug $(go list ./...) ``` -------------------------------- ### Run go-check-sumtype on packages Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Provide package paths to go-check-sumtype to check for exhaustiveness. This example excludes vendored directories. ```bash $ go-check-sumtype $(go list ./... | grep -v vendor) ``` -------------------------------- ### Check Exhaustiveness of a Type Switch Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md This example demonstrates a sum type declaration and a type switch that is missing a case, which go-check-sumtype will flag. ```go package main //sumtype:decl type MySumType interface { sealed() } type VariantA struct{} func (*VariantA) sealed() {} type VariantB struct{} func (*VariantB) sealed() {} func main() { switch MySumType(nil).(type) { case *VariantA: } } ``` -------------------------------- ### Run go-check-sumtype Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Execute the go-check-sumtype command with no arguments for usage information. ```bash $ go-check-sumtype ``` -------------------------------- ### Run Function Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt The primary exported function `Run` accepts a slice of loaded `*packages.Package` and a `Config`, then returns all exhaustiveness and declaration errors found. It's the main entry point for programmatic use. ```APIDOC ## `Run` — Programmatic API for Custom Linting Pipelines `Run` is the primary exported function. It accepts a slice of loaded `*packages.Package` and a `Config`, then returns all exhaustiveness and declaration errors found. ### Function Signature ```go func Run(pkgs []*packages.Package, cfg Config) []Error ``` ### Parameters - **pkgs** (`[]*packages.Package`) - A slice of loaded Go packages to analyze. - **cfg** (`Config`) - Configuration options for the analysis. ### Returns - `[]Error` - A slice of errors found during the analysis. Each error implements the `Error` interface. ### Example Usage ```go package main import ( gochecksumtype "github.com/alecthomas/go-check-sumtype" "golang.org/x/tools/go/packages" ) func main() { conf := &packages.Config{ Mode: packages.NeedSyntax | packages.NeedTypesInfo, } pkgs, err := packages.Load(conf, "./...") // ... handle error ... config := gochecksumtype.Config{ DefaultSignifiesExhaustive: true, IncludeSharedInterfaces: false, } errs := gochecksumtype.Run(pkgs, config) // ... process errors ... } ``` ``` -------------------------------- ### Run Programmatic API for Custom Linting Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt Use the `Run` function to programmatically check sum type exhaustiveness. Load packages with necessary analysis modes and configure the checker. Errors implement the `gochecksumtype.Error` interface for detailed reporting. ```go package main import ( "fmt" "log" gochecksumtype "github.com/alecthomas/go-check-sumtype" "golang.org/x/tools/go/packages" ) func main() { // Load packages with the required analysis modes conf := &packages.Config{ Mode: packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedImports | packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles, Tests: false, // test packages can cause false positives } pkgs, err := packages.Load(conf, "./...") if err != nil { log.Fatal(err) } config := gochecksumtype.Config{ DefaultSignifiesExhaustive: true, IncludeSharedInterfaces: false, } errs := gochecksumtype.Run(pkgs, config) if len(errs) == 0 { fmt.Println("All sum type switches are exhaustive.") return } for _, e := range errs { // Each error implements the gochecksumtype.Error interface: // Pos() token.Position and Error() string if posErr, ok := e.(gochecksumtype.Error); ok { fmt.Printf("at %s: %s\n", posErr.Pos(), posErr.Error()) } else { fmt.Println(e) } } // Example output: // at shapes/shapes.go:35:2: exhaustiveness check failed for sum type 'Shape' // (from shapes/shapes.go:8:6): missing cases for Triangle } ``` -------------------------------- ### Config Struct Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt The `Config` struct provides fine-grained control over the analysis performed by the `Run` function. ```APIDOC ## `Config` Struct — Analysis Configuration The `Config` struct allows customization of the `go-check-sumtype` analysis. ### Fields - **DefaultSignifiesExhaustive** (`bool`) - If true, types without a `//sumtype:decl` comment are assumed to be exhaustive. - **IncludeSharedInterfaces** (`bool`) - If true, variants that implement a shared sub-interface listed in the switch are considered covered. ### Example Usage ```go config := gochecksumtype.Config{ DefaultSignifiesExhaustive: true, IncludeSharedInterfaces: false, } errs := gochecksumtype.Run(pkgs, config) ``` ``` -------------------------------- ### Interface-Based Variant Grouping with -include-shared-interfaces Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt Enable `IncludeSharedInterfaces` to consider variants implementing a shared sub-interface as covered. This reduces the need to explicitly list every concrete type in a switch if they all satisfy a common interface. ```go package transport //sumtype:decl type Message interface{ message() } type Sendable interface { message() Send() error } type EmailMessage struct{} func (e EmailMessage) message() {} func (e EmailMessage) Send() error { return nil } type SMSMessage struct{} func (s SMSMessage) message() {} func (s SMSMessage) Send() error { return nil } type LogMessage struct{} func (l LogMessage) message() {} // With -include-shared-interfaces=true: // Listing Sendable covers both EmailMessage and SMSMessage — no error reported. // LogMessage must still be listed explicitly. func handleMessage(m Message) { switch m.(type) { case Sendable: // covers EmailMessage and SMSMessage // ... case LogMessage: // ... } } ``` ```bash go-check-sumtype -include-shared-interfaces=true ./transport/... # No output — all variants covered via shared interface grouping ``` -------------------------------- ### Typed Error Handling with Pos() Method Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt Errors from `go-check-sumtype` implement the `Error` interface, providing a `Pos()` method for precise source location. This allows for structured error reporting, useful for IDEs or automated review tools. ```go // Error interface defined by go-check-sumtype type Error interface { error Pos() token.Position } // Concrete error types returned: // - inexhaustiveError — type switch is missing one or more variant cases // - unsealedError — declared sum type interface has no unexported method // - notFoundError — declared type name not found in package // - notInterfaceError — declared type is not an interface errs := gochecksumtype.Run(pkgs, config) for _, e := range errs { if typed, ok := e.(gochecksumtype.Error); ok { pos := typed.Pos() fmt.Printf("file=%s line=%d col=%d msg=%s\n", pos.Filename, pos.Line, pos.Column, typed.Error()) } } // Output examples: // file=./shapes/shapes.go line=35 col=2 // msg=exhaustiveness check failed for sum type 'Shape': missing cases for Triangle // // file=./mytype/types.go line=10 col=1 // msg=interface 'MyType' is not sealed (sealing requires at least one unexported method) ``` -------------------------------- ### Configuring Exhaustiveness Rules Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt The Config struct controls whether a default clause satisfies exhaustiveness checks and whether shared interfaces are included. ```go type Config struct { DefaultSignifiesExhaustive bool IncludeSharedInterfaces bool } ``` ```go // DefaultSignifiesExhaustive = true (default): // A non-panicking default clause satisfies exhaustiveness checks. switch s.(type) { case Circle: // ... default: // OK — default clause present, no error reported } ``` ```go // DefaultSignifiesExhaustive = false: // A default clause does NOT bypass exhaustiveness. All variants must be listed. // go-check-sumtype -default-signifies-exhaustive=false ./... ``` ```go // Special case: a default clause that always panics NEVER satisfies exhaustiveness // regardless of DefaultSignifiesExhaustive. switch s.(type) { case Circle: // ... default: panic("unreachable") // exhaustiveness check still runs — Triangle and Rectangle are missing } ``` -------------------------------- ### Declare a Sum Type Interface Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Use the '//sumtype:decl' comment to mark an interface as a sum type. The interface must be sealed with an unexported method. ```go //sumtype:decl type MySumType interface { sealed() } ``` -------------------------------- ### Error Interface Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt All errors returned by `Run` implement the `Error` interface, which extends the standard `error` with a `Pos()` method for precise source location reporting. ```APIDOC ## `Error` Interface — Typed Error Handling All errors returned by `Run` implement the `Error` interface, which extends the standard `error` with a `Pos()` method for precise source location reporting. ### Interface Definition ```go type Error interface { error Pos() token.Position } ``` ### Concrete Error Types - `inexhaustiveError` — type switch is missing one or more variant cases - `unsealedError` — declared sum type interface has no unexported method - `notFoundError` — declared type name not found in package - `notInterfaceError` — declared type is not an interface ### Example Usage ```go errs := gochecksumtype.Run(pkgs, config) for _, e := range errs { if typed, ok := e.(gochecksumtype.Error); ok { pos := typed.Pos() fmt.Printf("file=%s line=%d col=%d msg=%s\n", pos.Filename, pos.Line, pos.Column, typed.Error()) } } ``` ``` -------------------------------- ### Include Shared Interfaces in Checks Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Set '-include-shared-interfaces=true' to include shared interfaces in exhaustiveness checks, allowing for more flexible switch statements. ```bash go-check-sumtype -include-shared-interfaces=true ``` -------------------------------- ### Declare a Sum Type with //sumtype:decl Source: https://context7.com/alecthomas/go-check-sumtype/llms.txt Mark an interface as a sum type by placing '//sumtype:decl' immediately before its declaration. The interface must be sealed with at least one unexported method. ```go package shapes //sumtype:decl type Shape interface { // area is unexported — this seals the interface, restricting // implementations to types within this package only. area() float64 } type Circle struct{ Radius float64 } func (c Circle) area() float64 { return 3.14159 * c.Radius * c.Radius } type Rectangle struct{ Width, Height float64 } func (r Rectangle) area() float64 { return r.Width * r.Height } type Triangle struct{ Base, Height float64 } func (t Triangle) area() float64 { return 0.5 * t.Base * t.Height } ``` ```go // PASS: all variants covered func describeShape(s Shape) string { switch s.(type) { case Circle: return "circle" case Rectangle: return "rectangle" case Triangle: return "triangle" } return "" } ``` ```go // FAIL: go-check-sumtype will report: // shapes.go:35:2: exhaustiveness check failed for sum type 'Shape': missing cases for Triangle func describeShapeIncomplete(s Shape) string { switch s.(type) { case Circle: return "circle" case Rectangle: return "rectangle" } return "" } ``` -------------------------------- ### Exhaustiveness Check Failure Message Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md The output from go-check-sumtype when a type switch statement is not exhaustive, indicating the missing cases. ```bash $ sumtype mysumtype.go mysumtype.go:18:2: exhaustiveness check failed for sum type 'MySumType': missing cases for VariantB ``` -------------------------------- ### Disable Default Clause Exhaustiveness Check Source: https://github.com/alecthomas/go-check-sumtype/blob/master/README.md Use the '-default-signifies-exhaustive=false' flag to prevent 'default' clauses from automatically passing exhaustiveness checks. ```bash go-check-sumtype -default-signifies-exhaustive=false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.