// 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. //go:build ignore // This program is run via "go generate" (via a directive in sort.go) // to generate implementation variants of the underlying sorting algorithm. // When passed the -generic flag it generates generic variants of sorting; // otherwise it generates the non-generic variants used by the sort package. package main import ( "bytes" "flag" "fmt" "go/format" "log" "os" "text/template" ) type Variant struct { // Name is the variant name: should be unique among variants. Name string // Path is the file path into which the generator will emit the code for this // variant. Path string // Package is the package this code will be emitted into. Package string // Imports is the imports needed for this package. Imports string // FuncSuffix is appended to all function names in this variant's code. All // suffixes should be unique within a package. FuncSuffix string // DataType is the type of the data parameter of functions in this variant's // code. DataType string // TypeParam is the optional type parameter for the function. TypeParam string // ExtraParam is an extra parameter to pass to the function. Should begin with // ", " to separate from other params. ExtraParam string // ExtraArg is an extra argument to pass to calls between functions; typically // it invokes ExtraParam. Should begin with ", " to separate from other args. ExtraArg string // Funcs is a map of functions used from within the template. The following // functions are expected to exist: // // Less (name, i, j): // emits a comparison expression that checks if the value `name` at // index `i` is smaller than at index `j`. // // Swap (name, i, j): // emits a statement that performs a data swap between elements `i` and // `j` of the value `name`. Funcs template.FuncMap } var ( traditionalVariants = []Variant{ Variant{ Name: "interface", Path: "zsortinterface.go", Package: "sort", Imports: "", FuncSuffix: "", TypeParam: "", ExtraParam: "", ExtraArg: "", DataType: "Interface", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("%s.Less(%s, %s)", name, i, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s.Swap(%s, %s)", name, i, j) }, }, }, Variant{ Name: "func", Path: "zsortfunc.go", Package: "sort", Imports: "", FuncSuffix: "_func", TypeParam: "", ExtraParam: "", ExtraArg: "", DataType: "lessSwap", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("%s.Less(%s, %s)", name, i, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s.Swap(%s, %s)", name, i, j) }, }, }, } genericVariants = []Variant{ Variant{ Name: "generic_ordered", Path: "zsortordered.go", Package: "slices", Imports: "import \"cmp\"\n", FuncSuffix: "Ordered", TypeParam: "[E cmp.Ordered]", ExtraParam: "", ExtraArg: "", DataType: "[]E", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("cmp.Less(%s[%s], %s[%s])", name, i, name, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s[%s], %s[%s] = %s[%s], %s[%s]", name, i, name, j, name, j, name, i) }, }, }, Variant{ Name: "generic_func", Path: "zsortanyfunc.go", Package: "slices", FuncSuffix: "CmpFunc", TypeParam: "[E any]", ExtraParam: ", cmp func(a, b E) int", ExtraArg: ", cmp", DataType: "[]E", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("(cmp(%s[%s], %s[%s]) < 0)", name, i, name, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s[%s], %s[%s] = %s[%s], %s[%s]", name, i, name, j, name, j, name, i) }, }, }, } expVariants = []Variant{ Variant{ Name: "exp_ordered", Path: "zsortordered.go", Package: "slices", Imports: "import \"golang.org/x/exp/constraints\"\n", FuncSuffix: "Ordered", TypeParam: "[E constraints.Ordered]", ExtraParam: "", ExtraArg: "", DataType: "[]E", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("cmpLess(%s[%s], %s[%s])", name, i, name, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s[%s], %s[%s] = %s[%s], %s[%s]", name, i, name, j, name, j, name, i) }, }, }, Variant{ Name: "exp_func", Path: "zsortanyfunc.go", Package: "slices", FuncSuffix: "CmpFunc", TypeParam: "[E any]", ExtraParam: ", cmp func(a, b E) int", ExtraArg: ", cmp", DataType: "[]E", Funcs: template.FuncMap{ "Less": func(name, i, j string) string { return fmt.Sprintf("(cmp(%s[%s], %s[%s]) < 0)", name, i, name, j) }, "Swap": func(name, i, j string) string { return fmt.Sprintf("%s[%s], %s[%s] = %s[%s], %s[%s]", name, i, name, j, name, j, name, i) }, }, }, } ) func main() { genGeneric := flag.Bool("generic", false, "generate generic versions") genExp := flag.Bool("exp", false, "generate x/exp/slices versions") flag.Parse() var variants []Variant if *genExp { variants = expVariants } else if *genGeneric { variants = genericVariants } else { variants = traditionalVariants } for i := range variants { generate(&variants[i]) } } // generate generates the code for variant `v` into a file named by `v.Path`. func generate(v *Variant) { // Parse templateCode anew for each variant because Parse requires Funcs to be // registered, and it helps type-check the funcs. tmpl, err := template.New("gen").Funcs(v.Funcs).Parse(templateCode) if err != nil { log.Fatal("template Parse:", err) } var out bytes.Buffer err = tmpl.Execute(&out, v) if err != nil { log.Fatal("template Execute:", err) } formatted, err := format.Source(out.Bytes()) if err != nil { log.Fatal("format:", err) } if err := os.WriteFile(v.Path, formatted, 0644); err != nil { log.Fatal("WriteFile:", err) } } var templateCode = `// Code generated by gen_sort_variants.go; DO NOT EDIT. // Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package {{.Package}} {{.Imports}} // insertionSort{{.FuncSuffix}} sorts data[a:b] using insertion sort. func insertionSort{{.FuncSuffix}}{{.TypeParam}}(data {{.DataType}}, a, b int {{.ExtraParam}}) { for i := a + 1; i < b; i++ { for j := i; j > a && {{Less "data" "j" "j-1"}}; j-- { {{Swap "data" "j" "j-1"}} } } } // siftDown{{.FuncSuffix}} implements the heap property on data[lo:hi]. // first is an offset into the array where the root of the heap lies. func siftDown{{.FuncSuffix}}{{.TypeParam}}(data {{.DataType}}, lo, hi, first int {{.ExtraParam}}) { root := lo for { child := 2*root + 1 if child >= hi { break } if child+1 < hi && {{Less "data" "first+child" "first+child+1"}} { child++ } if !{{Less "data" "first+root" "first+child"}} { return } {{Swap "data" "first+root" "first+child"}} root = child } } func heapSort{{.FuncSuffix}}{{.TypeParam}}(data {{.DataType}}, a, b int {{.ExtraParam}}) { first := a lo := 0 hi := b - a // Build heap with greatest element at top. for i := (hi - 1) / 2; i >= 0; i-- { siftDown{{.FuncSuffix}}(data, i, hi, first {{.ExtraArg}}) } // Pop elements, largest first, into end of data. for i := hi - 1; i >= 0; i-- { {{Swap "data" "first" "first+i"}} siftDown{{.FuncSuffix}}(data, lo, i, first {{.ExtraArg}}) } } // pdqsort{{.FuncSuffix}} sorts data[a:b]. // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort. // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf // C++ implementation: https://github.com/orlp/pdqsort // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/ // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort. func pdqsort{{.FuncSuffix}}{{.TypeParam}}(data {{.DataType}}, a, b, limit int {{.ExtraParam}}) { const maxInsertion = 12 var ( wasBalanced = true // whether the last partitioning was reasonably balanced wasPartitioned = true // whether the slice was already partitioned ) for { length := b - a if length <= maxInsertion { insertionSort{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) return } // Fall back to heapsort if too many bad choices were made. if limit == 0 { heapSort{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) return } // If the last partitioning was imbalanced, we need to breaking patterns. if !wasBalanced { breakPatterns{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) limit-- } pivot, hint := choosePivot{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) if hint == decreasingHint { reverseRange{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) // The chosen pivot was pivot-a elements after the start of the array. // After reversing it is pivot-a elements before the end of the array. // The idea came from Rust's implementation. pivot = (b - 1) - (pivot - a) hint = increasingHint } // The slice is likely already sorted. if wasBalanced && wasPartitioned && hint == increasingHint { if partialInsertionSort{{.FuncSuffix}}(data, a, b {{.ExtraArg}}) { return } } // Probably the slice contains many duplicate elements, partition the slice into // elements equal to and elements greater than the pivot. if a > 0 && !{{Less "data" "a-1" "pivot"}} { mid := partitionEqual{{.FuncSuffix}}(data, a, b, pivot {{.ExtraArg}}) a = mid continue } mid, alreadyPartitioned := partition{{.FuncSuffix}}(data, a, b, pivot {{.ExtraArg}}) wasPartitioned = alreadyPartitioned leftLen, rightLen := mid-a, b-mid balanceThreshold := length / 8 if leftLen < rightLen { wasBalanced = leftLen >= balanceThreshold pdqsort{{.FuncSuffix}}(data, a, mid, limit {{.ExtraArg}}) a = mid + 1 } else { wasBalanced = rightLen >= balanceThreshold pdqsort{{.FuncSuffix}}(data, mid+1, b, limit {{.ExtraArg}}) b = mid } } } // partition{{.FuncSuffix}} does one quicksort partition. // Let p = data[pivot] // Moves elements in data[a:b] around, so that data[i]
=p for i