pkg.go 16.1 KB
Newer Older
Rob Pike's avatar
Rob Pike committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/build"
	"go/doc"
	"go/format"
	"go/parser"
	"go/token"
Rob Pike's avatar
Rob Pike committed
16
	"io"
Rob Pike's avatar
Rob Pike committed
17 18
	"log"
	"os"
19 20
	"path/filepath"
	"strings"
Rob Pike's avatar
Rob Pike committed
21 22 23 24
	"unicode"
	"unicode/utf8"
)

25 26 27 28 29 30
const (
	punchedCardWidth = 80 // These things just won't leave us alone.
	indentedWidth    = punchedCardWidth - len(indent)
	indent           = "    "
)

Rob Pike's avatar
Rob Pike committed
31
type Package struct {
Rob Pike's avatar
Rob Pike committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
	writer     io.Writer // Destination for output.
	name       string    // Package name, json for encoding/json.
	userPath   string    // String the user used to find this package.
	unexported bool
	matchCase  bool
	pkg        *ast.Package // Parsed package.
	file       *ast.File    // Merged from all files in the package
	doc        *doc.Package
	build      *build.Package
	fs         *token.FileSet // Needed for printing.
	buf        bytes.Buffer
}

type PackageError string // type returned by pkg.Fatalf.

func (p PackageError) Error() string {
	return string(p)
}

51 52 53 54 55 56 57 58 59 60 61 62
// prettyPath returns a version of the package path that is suitable for an
// error message. It obeys the import comment if present. Also, since
// pkg.build.ImportPath is sometimes the unhelpful "" or ".", it looks for a
// directory name in GOROOT or GOPATH if that happens.
func (pkg *Package) prettyPath() string {
	path := pkg.build.ImportComment
	if path == "" {
		path = pkg.build.ImportPath
	}
	if path != "." && path != "" {
		return path
	}
63 64 65
	// Convert the source directory into a more useful path.
	// Also convert everything to slash-separated paths for uniform handling.
	path = filepath.Clean(filepath.ToSlash(pkg.build.Dir))
66 67
	// Can we find a decent prefix?
	goroot := filepath.Join(build.Default.GOROOT, "src")
68 69
	if p, ok := trim(path, filepath.ToSlash(goroot)); ok {
		return p
70 71
	}
	for _, gopath := range splitGopath() {
72 73
		if p, ok := trim(path, filepath.ToSlash(gopath)); ok {
			return p
74 75 76 77 78
		}
	}
	return path
}

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
// trim trims the directory prefix from the path, paying attention
// to the path separator. If they are the same string or the prefix
// is not present the original is returned. The boolean reports whether
// the prefix is present. That path and prefix have slashes for separators.
func trim(path, prefix string) (string, bool) {
	if !strings.HasPrefix(path, prefix) {
		return path, false
	}
	if path == prefix {
		return path, true
	}
	if path[len(prefix)] == '/' {
		return path[len(prefix)+1:], true
	}
	return path, false // Textual prefix but not a path prefix.
}

Rob Pike's avatar
Rob Pike committed
96 97 98 99 100 101
// pkg.Fatalf is like log.Fatalf, but panics so it can be recovered in the
// main do function, so it doesn't cause an exit. Allows testing to work
// without running a subprocess. The log prefix will be added when
// logged in main; it is not added here.
func (pkg *Package) Fatalf(format string, args ...interface{}) {
	panic(PackageError(fmt.Sprintf(format, args...)))
Rob Pike's avatar
Rob Pike committed
102 103 104 105
}

// parsePackage turns the build package we found into a parsed package
// we can then use to generate documentation.
Rob Pike's avatar
Rob Pike committed
106
func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Package {
Rob Pike's avatar
Rob Pike committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
	fs := token.NewFileSet()
	// include tells parser.ParseDir which files to include.
	// That means the file must be in the build package's GoFiles or CgoFiles
	// list only (no tag-ignored files, tests, swig or other non-Go files).
	include := func(info os.FileInfo) bool {
		for _, name := range pkg.GoFiles {
			if name == info.Name() {
				return true
			}
		}
		for _, name := range pkg.CgoFiles {
			if name == info.Name() {
				return true
			}
		}
		return false
	}
	pkgs, err := parser.ParseDir(fs, pkg.Dir, include, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}
	// Make sure they are all in one package.
	if len(pkgs) != 1 {
Rob Pike's avatar
Rob Pike committed
130
		log.Fatalf("multiple packages in directory %s", pkg.Dir)
Rob Pike's avatar
Rob Pike committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144
	}
	astPkg := pkgs[pkg.Name]

	// TODO: go/doc does not include typed constants in the constants
	// list, which is what we want. For instance, time.Sunday is of type
	// time.Weekday, so it is defined in the type but not in the
	// Consts list for the package. This prevents
	//	go doc time.Sunday
	// from finding the symbol. Work around this for now, but we
	// should fix it in go/doc.
	// A similar story applies to factory functions.
	docPkg := doc.New(astPkg, pkg.ImportPath, doc.AllDecls)
	for _, typ := range docPkg.Types {
		docPkg.Consts = append(docPkg.Consts, typ.Consts...)
145
		docPkg.Vars = append(docPkg.Vars, typ.Vars...)
Rob Pike's avatar
Rob Pike committed
146 147 148 149
		docPkg.Funcs = append(docPkg.Funcs, typ.Funcs...)
	}

	return &Package{
Rob Pike's avatar
Rob Pike committed
150
		writer:   writer,
Rob Pike's avatar
Rob Pike committed
151 152 153 154 155 156 157
		name:     pkg.Name,
		userPath: userPath,
		pkg:      astPkg,
		file:     ast.MergePackageFiles(astPkg, 0),
		doc:      docPkg,
		build:    pkg,
		fs:       fs,
Rob Pike's avatar
Rob Pike committed
158 159 160
	}
}

Rob Pike's avatar
Rob Pike committed
161 162 163 164 165
func (pkg *Package) Printf(format string, args ...interface{}) {
	fmt.Fprintf(&pkg.buf, format, args...)
}

func (pkg *Package) flush() {
Rob Pike's avatar
Rob Pike committed
166
	_, err := pkg.writer.Write(pkg.buf.Bytes())
Rob Pike's avatar
Rob Pike committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180
	if err != nil {
		log.Fatal(err)
	}
	pkg.buf.Reset() // Not needed, but it's a flush.
}

var newlineBytes = []byte("\n\n") // We never ask for more than 2.

// newlines guarantees there are n newlines at the end of the buffer.
func (pkg *Package) newlines(n int) {
	for !bytes.HasSuffix(pkg.buf.Bytes(), newlineBytes[:n]) {
		pkg.buf.WriteRune('\n')
	}
}
Rob Pike's avatar
Rob Pike committed
181 182 183 184

// emit prints the node.
func (pkg *Package) emit(comment string, node ast.Node) {
	if node != nil {
Rob Pike's avatar
Rob Pike committed
185
		err := format.Node(&pkg.buf, pkg.fs, node)
Rob Pike's avatar
Rob Pike committed
186 187 188
		if err != nil {
			log.Fatal(err)
		}
Rob Pike's avatar
Rob Pike committed
189
		if comment != "" {
190
			pkg.newlines(1)
191
			doc.ToText(&pkg.buf, comment, "    ", indent, indentedWidth)
192 193 194
			pkg.newlines(2) // Blank line after comment to separate from next item.
		} else {
			pkg.newlines(1)
Rob Pike's avatar
Rob Pike committed
195 196 197 198
		}
	}
}

Rob Pike's avatar
Rob Pike committed
199 200
var formatBuf bytes.Buffer // Reusable to avoid allocation.

Rob Pike's avatar
Rob Pike committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
// formatNode is a helper function for printing.
func (pkg *Package) formatNode(node ast.Node) []byte {
	formatBuf.Reset()
	format.Node(&formatBuf, pkg.fs, node)
	return formatBuf.Bytes()
}

// oneLineFunc prints a function declaration as a single line.
func (pkg *Package) oneLineFunc(decl *ast.FuncDecl) {
	decl.Doc = nil
	decl.Body = nil
	pkg.emit("", decl)
}

// oneLineValueGenDecl prints a var or const declaration as a single line.
func (pkg *Package) oneLineValueGenDecl(decl *ast.GenDecl) {
	decl.Doc = nil
	dotDotDot := ""
	if len(decl.Specs) > 1 {
		dotDotDot = " ..."
	}
	// Find the first relevant spec.
	for i, spec := range decl.Specs {
		valueSpec := spec.(*ast.ValueSpec) // Must succeed; we can't mix types in one genDecl.
		if !isExported(valueSpec.Names[0].Name) {
			continue
		}
		typ := ""
		if valueSpec.Type != nil {
			typ = fmt.Sprintf(" %s", pkg.formatNode(valueSpec.Type))
		}
		val := ""
		if i < len(valueSpec.Values) && valueSpec.Values[i] != nil {
			val = fmt.Sprintf(" = %s", pkg.formatNode(valueSpec.Values[i]))
		}
Rob Pike's avatar
Rob Pike committed
236
		pkg.Printf("%s %s%s%s%s\n", decl.Tok, valueSpec.Names[0], typ, val, dotDotDot)
Rob Pike's avatar
Rob Pike committed
237 238 239 240 241 242 243 244 245 246
		break
	}
}

// oneLineTypeDecl prints a type declaration as a single line.
func (pkg *Package) oneLineTypeDecl(spec *ast.TypeSpec) {
	spec.Doc = nil
	spec.Comment = nil
	switch spec.Type.(type) {
	case *ast.InterfaceType:
Rob Pike's avatar
Rob Pike committed
247
		pkg.Printf("type %s interface { ... }\n", spec.Name)
Rob Pike's avatar
Rob Pike committed
248
	case *ast.StructType:
Rob Pike's avatar
Rob Pike committed
249
		pkg.Printf("type %s struct { ... }\n", spec.Name)
Rob Pike's avatar
Rob Pike committed
250
	default:
Rob Pike's avatar
Rob Pike committed
251
		pkg.Printf("type %s %s\n", spec.Name, pkg.formatNode(spec.Type))
Rob Pike's avatar
Rob Pike committed
252 253 254 255 256
	}
}

// packageDoc prints the docs for the package (package doc plus one-liners of the rest).
func (pkg *Package) packageDoc() {
Rob Pike's avatar
Rob Pike committed
257
	defer pkg.flush()
258 259 260
	if pkg.showInternals() {
		pkg.packageClause(false)
	}
Rob Pike's avatar
Rob Pike committed
261

262
	doc.ToText(&pkg.buf, pkg.doc.Doc, "", indent, indentedWidth)
263 264 265 266 267 268
	pkg.newlines(1)

	if !pkg.showInternals() {
		// Show only package docs for commands.
		return
	}
Rob Pike's avatar
Rob Pike committed
269

270
	pkg.newlines(2) // Guarantee blank line before the components.
Rob Pike's avatar
Rob Pike committed
271 272 273 274
	pkg.valueSummary(pkg.doc.Consts)
	pkg.valueSummary(pkg.doc.Vars)
	pkg.funcSummary(pkg.doc.Funcs)
	pkg.typeSummary()
275
	pkg.bugs()
Rob Pike's avatar
Rob Pike committed
276 277
}

278 279 280 281 282 283 284 285
// showInternals reports whether we should show the internals
// of a package as opposed to just the package docs.
// Used to decide whether to suppress internals for commands.
// Called only by Package.packageDoc.
func (pkg *Package) showInternals() bool {
	return pkg.pkg.Name != "main" || showCmd
}

Rob Pike's avatar
Rob Pike committed
286 287 288 289 290 291 292 293 294 295
// packageClause prints the package clause.
// The argument boolean, if true, suppresses the output if the
// user's argument is identical to the actual package path or
// is empty, meaning it's the current directory.
func (pkg *Package) packageClause(checkUserPath bool) {
	if checkUserPath {
		if pkg.userPath == "" || pkg.userPath == pkg.build.ImportPath {
			return
		}
	}
Rob Pike's avatar
Rob Pike committed
296 297 298 299
	importPath := pkg.build.ImportComment
	if importPath == "" {
		importPath = pkg.build.ImportPath
	}
Rob Pike's avatar
Rob Pike committed
300
	pkg.Printf("package %s // import %q\n\n", pkg.name, importPath)
Rob Pike's avatar
Rob Pike committed
301
	if importPath != pkg.build.ImportPath {
Rob Pike's avatar
Rob Pike committed
302
		pkg.Printf("WARNING: package source is installed in %q\n", pkg.build.ImportPath)
Rob Pike's avatar
Rob Pike committed
303 304 305 306 307 308
	}
}

// valueSummary prints a one-line summary for each set of values and constants.
func (pkg *Package) valueSummary(values []*doc.Value) {
	for _, value := range values {
309
		pkg.oneLineValueGenDecl(value.Decl)
Rob Pike's avatar
Rob Pike committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	}
}

// funcSummary prints a one-line summary for each function.
func (pkg *Package) funcSummary(funcs []*doc.Func) {
	for _, fun := range funcs {
		decl := fun.Decl
		// Exported functions only. The go/doc package does not include methods here.
		if isExported(fun.Name) {
			pkg.oneLineFunc(decl)
		}
	}
}

// typeSummary prints a one-line summary for each type.
func (pkg *Package) typeSummary() {
	for _, typ := range pkg.doc.Types {
		for _, spec := range typ.Decl.Specs {
			typeSpec := spec.(*ast.TypeSpec) // Must succeed.
			if isExported(typeSpec.Name.Name) {
				pkg.oneLineTypeDecl(typeSpec)
			}
		}
	}
}

336 337 338 339 340 341 342 343 344 345 346 347
// bugs prints the BUGS information for the package.
// TODO: Provide access to TODOs and NOTEs as well (very noisy so off by default)?
func (pkg *Package) bugs() {
	if pkg.doc.Notes["BUG"] == nil {
		return
	}
	pkg.Printf("\n")
	for _, note := range pkg.doc.Notes["BUG"] {
		pkg.Printf("%s: %v\n", "BUG", note.Body)
	}
}

348 349 350
// findValues finds the doc.Values that describe the symbol.
func (pkg *Package) findValues(symbol string, docValues []*doc.Value) (values []*doc.Value) {
	for _, value := range docValues {
Rob Pike's avatar
Rob Pike committed
351 352
		for _, name := range value.Names {
			if match(symbol, name) {
353
				values = append(values, value)
Rob Pike's avatar
Rob Pike committed
354 355 356
			}
		}
	}
357
	return
Rob Pike's avatar
Rob Pike committed
358 359
}

360 361
// findFuncs finds the doc.Funcs that describes the symbol.
func (pkg *Package) findFuncs(symbol string) (funcs []*doc.Func) {
Rob Pike's avatar
Rob Pike committed
362 363
	for _, fun := range pkg.doc.Funcs {
		if match(symbol, fun.Name) {
364
			funcs = append(funcs, fun)
Rob Pike's avatar
Rob Pike committed
365 366
		}
	}
367
	return
Rob Pike's avatar
Rob Pike committed
368 369
}

370
// findTypes finds the doc.Types that describes the symbol.
371
// If symbol is empty, it finds all exported types.
372
func (pkg *Package) findTypes(symbol string) (types []*doc.Type) {
Rob Pike's avatar
Rob Pike committed
373
	for _, typ := range pkg.doc.Types {
374
		if symbol == "" && isExported(typ.Name) || match(symbol, typ.Name) {
375
			types = append(types, typ)
Rob Pike's avatar
Rob Pike committed
376 377
		}
	}
378
	return
Rob Pike's avatar
Rob Pike committed
379 380 381
}

// findTypeSpec returns the ast.TypeSpec within the declaration that defines the symbol.
382
// The name must match exactly.
Rob Pike's avatar
Rob Pike committed
383 384 385
func (pkg *Package) findTypeSpec(decl *ast.GenDecl, symbol string) *ast.TypeSpec {
	for _, spec := range decl.Specs {
		typeSpec := spec.(*ast.TypeSpec) // Must succeed.
386
		if symbol == typeSpec.Name.Name {
Rob Pike's avatar
Rob Pike committed
387 388 389 390 391 392
			return typeSpec
		}
	}
	return nil
}

393 394
// symbolDoc prints the docs for symbol. There may be multiple matches.
// If symbol matches a type, output includes its methods factories and associated constants.
395
// If there is no top-level symbol, symbolDoc looks for methods that match.
396
func (pkg *Package) symbolDoc(symbol string) bool {
Rob Pike's avatar
Rob Pike committed
397
	defer pkg.flush()
398
	found := false
Rob Pike's avatar
Rob Pike committed
399
	// Functions.
400
	for _, fun := range pkg.findFuncs(symbol) {
Rob Pike's avatar
Rob Pike committed
401 402 403
		if !found {
			pkg.packageClause(true)
		}
Rob Pike's avatar
Rob Pike committed
404 405 406 407
		// Symbol is a function.
		decl := fun.Decl
		decl.Body = nil
		pkg.emit(fun.Doc, decl)
408
		found = true
Rob Pike's avatar
Rob Pike committed
409 410
	}
	// Constants and variables behave the same.
411 412 413
	values := pkg.findValues(symbol, pkg.doc.Consts)
	values = append(values, pkg.findValues(symbol, pkg.doc.Vars)...)
	for _, value := range values {
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
		// Print each spec only if there is at least one exported symbol in it.
		// (See issue 11008.)
		// TODO: Should we elide unexported symbols from a single spec?
		// It's an unlikely scenario, probably not worth the trouble.
		// TODO: Would be nice if go/doc did this for us.
		specs := make([]ast.Spec, 0, len(value.Decl.Specs))
		for _, spec := range value.Decl.Specs {
			vspec := spec.(*ast.ValueSpec)
			for _, ident := range vspec.Names {
				if isExported(ident.Name) {
					specs = append(specs, vspec)
					break
				}
			}
		}
		if len(specs) == 0 {
			continue
		}
		value.Decl.Specs = specs
Rob Pike's avatar
Rob Pike committed
433 434 435
		if !found {
			pkg.packageClause(true)
		}
Rob Pike's avatar
Rob Pike committed
436
		pkg.emit(value.Doc, value.Decl)
437
		found = true
Rob Pike's avatar
Rob Pike committed
438 439
	}
	// Types.
440
	for _, typ := range pkg.findTypes(symbol) {
Rob Pike's avatar
Rob Pike committed
441 442 443
		if !found {
			pkg.packageClause(true)
		}
444 445
		decl := typ.Decl
		spec := pkg.findTypeSpec(decl, typ.Name)
446
		trimUnexportedElems(spec)
447 448 449 450 451 452
		// If there are multiple types defined, reduce to just this one.
		if len(decl.Specs) > 1 {
			decl.Specs = []ast.Spec{spec}
		}
		pkg.emit(typ.Doc, decl)
		// Show associated methods, constants, etc.
453 454 455
		if len(typ.Consts) > 0 || len(typ.Vars) > 0 || len(typ.Funcs) > 0 || len(typ.Methods) > 0 {
			pkg.Printf("\n")
		}
456 457 458 459 460 461 462
		pkg.valueSummary(typ.Consts)
		pkg.valueSummary(typ.Vars)
		pkg.funcSummary(typ.Funcs)
		pkg.funcSummary(typ.Methods)
		found = true
	}
	if !found {
463 464
		// See if there are methods.
		if !pkg.printMethodDoc("", symbol) {
465
			return false
466
		}
Rob Pike's avatar
Rob Pike committed
467
	}
468
	return true
Rob Pike's avatar
Rob Pike committed
469 470
}

471 472 473
// trimUnexportedElems modifies spec in place to elide unexported fields from
// structs and methods from interfaces (unless the unexported flag is set).
func trimUnexportedElems(spec *ast.TypeSpec) {
Rob Pike's avatar
Rob Pike committed
474
	if unexported {
Mikio Hara's avatar
Mikio Hara committed
475
		return
Rob Pike's avatar
Rob Pike committed
476
	}
477 478 479 480 481
	switch typ := spec.Type.(type) {
	case *ast.StructType:
		typ.Fields = trimUnexportedFields(typ.Fields, "fields")
	case *ast.InterfaceType:
		typ.Methods = trimUnexportedFields(typ.Methods, "methods")
Rob Pike's avatar
Rob Pike committed
482
	}
483 484 485 486
}

// trimUnexportedFields returns the field list trimmed of unexported fields.
func trimUnexportedFields(fields *ast.FieldList, what string) *ast.FieldList {
Rob Pike's avatar
Rob Pike committed
487
	trimmed := false
488 489 490
	list := make([]*ast.Field, 0, len(fields.List))
	for _, field := range fields.List {
		// Trims if any is unexported. Good enough in practice.
Rob Pike's avatar
Rob Pike committed
491 492 493 494 495 496 497 498 499 500 501 502
		ok := true
		for _, name := range field.Names {
			if !isExported(name.Name) {
				trimmed = true
				ok = false
				break
			}
		}
		if ok {
			list = append(list, field)
		}
	}
503 504 505 506 507 508
	if !trimmed {
		return fields
	}
	unexportedField := &ast.Field{
		Type: ast.NewIdent(""), // Hack: printer will treat this as a field with a named type.
		Comment: &ast.CommentGroup{
509
			List: []*ast.Comment{{Text: fmt.Sprintf("// Has unexported %s.\n", what)}},
510 511 512 513 514 515
		},
	}
	return &ast.FieldList{
		Opening: fields.Opening,
		List:    append(list, unexportedField),
		Closing: fields.Closing,
Rob Pike's avatar
Rob Pike committed
516 517 518
	}
}

519 520 521 522
// printMethodDoc prints the docs for matches of symbol.method.
// If symbol is empty, it prints all methods that match the name.
// It reports whether it found any methods.
func (pkg *Package) printMethodDoc(symbol, method string) bool {
Rob Pike's avatar
Rob Pike committed
523
	defer pkg.flush()
524 525
	types := pkg.findTypes(symbol)
	if types == nil {
526 527 528
		if symbol == "" {
			return false
		}
Rob Pike's avatar
Rob Pike committed
529
		pkg.Fatalf("symbol %s is not a type in package %s installed in %q", symbol, pkg.name, pkg.build.ImportPath)
Rob Pike's avatar
Rob Pike committed
530
	}
531 532 533 534 535 536 537 538 539
	found := false
	for _, typ := range types {
		for _, meth := range typ.Methods {
			if match(method, meth.Name) {
				decl := meth.Decl
				decl.Body = nil
				pkg.emit(meth.Doc, decl)
				found = true
			}
Rob Pike's avatar
Rob Pike committed
540 541
		}
	}
542 543 544 545
	return found
}

// methodDoc prints the docs for matches of symbol.method.
546
func (pkg *Package) methodDoc(symbol, method string) bool {
547
	defer pkg.flush()
548
	return pkg.printMethodDoc(symbol, method)
Rob Pike's avatar
Rob Pike committed
549 550 551 552 553 554 555 556 557
}

// match reports whether the user's symbol matches the program's.
// A lower-case character in the user's string matches either case in the program's.
// The program string must be exported.
func match(user, program string) bool {
	if !isExported(program) {
		return false
	}
Rob Pike's avatar
Rob Pike committed
558
	if matchCase {
Rob Pike's avatar
Rob Pike committed
559 560
		return user == program
	}
Rob Pike's avatar
Rob Pike committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
	for _, u := range user {
		p, w := utf8.DecodeRuneInString(program)
		program = program[w:]
		if u == p {
			continue
		}
		if unicode.IsLower(u) && simpleFold(u) == simpleFold(p) {
			continue
		}
		return false
	}
	return program == ""
}

// simpleFold returns the minimum rune equivalent to r
// under Unicode-defined simple case folding.
func simpleFold(r rune) rune {
	for {
		r1 := unicode.SimpleFold(r)
		if r1 <= r {
			return r1 // wrapped around, found min
		}
		r = r1
	}
}