aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

parse.go (32096B)


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"os"
      7 	"regexp"
      8 	"slices"
      9 	"strings"
     10 )
     11 
     12 var xrefPattern = regexp.MustCompile(`^\s*([A-Za-z0-9][A-Za-z0-9+_.-]*)\((\d+[A-Za-z]*)\)\s*$`)
     13 var groupPattern = regexp.MustCompile(`\{[A-Za-z][A-Za-z0-9_-]*\}`)
     14 var macroNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
     15 var manNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9+_.-]*$`)
     16 
     17 func parseNameSummary(line string) (string, string, bool) {
     18 	line = strings.TrimSpace(line)
     19 	idx := strings.IndexByte(line, ':')
     20 	if idx < 0 {
     21 		return "", "", false
     22 	}
     23 	return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true
     24 }
     25 
     26 func parseConditional(directive string, cfg Config, stack *ifStack, lineNo int) error {
     27 	name := directive
     28 	if fields := strings.Fields(directive); len(fields) != 0 {
     29 		name = fields[0]
     30 	}
     31 
     32 	switch name {
     33 	case "if", "ifdef", "ifndef", "elif", "else", "endif":
     34 	default:
     35 		if strings.HasPrefix(name, "if") || strings.HasPrefix(name, "elif") ||
     36 			strings.HasPrefix(name, "else") || strings.HasPrefix(name, "endif") {
     37 			return fmt.Errorf("line %d: unsupported preprocessor conditional %q", lineNo, directive)
     38 		}
     39 		return nil
     40 	}
     41 
     42 	switch name {
     43 	case "if":
     44 		if !strings.HasPrefix(directive, "if ") {
     45 			return fmt.Errorf("line %d: malformed #if directive", lineNo)
     46 		}
     47 		result, err := evalCondition(strings.TrimSpace(directive[3:]), cfg)
     48 		if err != nil {
     49 			return fmt.Errorf("line %d: %w", lineNo, err)
     50 		}
     51 		pa := stack.parentActive()
     52 		stack.push(pa && result, result)
     53 	case "ifdef", "ifndef":
     54 		prefix := name + " "
     55 		if !strings.HasPrefix(directive, prefix) {
     56 			return fmt.Errorf("line %d: malformed #%s directive", lineNo, name)
     57 		}
     58 		key := strings.TrimSpace(directive[len(prefix):])
     59 		if !macroNamePattern.MatchString(key) {
     60 			return fmt.Errorf("line %d: invalid macro name %q", lineNo, key)
     61 		}
     62 		if err := validateConditionalName(key); err != nil {
     63 			return fmt.Errorf("line %d: %w", lineNo, err)
     64 		}
     65 		_, defined := cfg[key]
     66 		result := defined
     67 		if name == "ifndef" {
     68 			result = !result
     69 		}
     70 		pa := stack.parentActive()
     71 		stack.push(pa && result, result)
     72 	case "else":
     73 		if directive != "else" {
     74 			return fmt.Errorf("line %d: malformed #else directive", lineNo)
     75 		}
     76 		top := stack.top()
     77 		if top == nil {
     78 			return fmt.Errorf("line %d: #else without #if", lineNo)
     79 		}
     80 		if top.elseSeen {
     81 			return fmt.Errorf("line %d: duplicate #else", lineNo)
     82 		}
     83 		pa := stack.parentActive()
     84 		top.active = pa && !top.seen
     85 		top.seen = true
     86 		top.elseSeen = true
     87 	case "elif":
     88 		if !strings.HasPrefix(directive, "elif ") {
     89 			return fmt.Errorf("line %d: malformed #elif directive", lineNo)
     90 		}
     91 		top := stack.top()
     92 		if top == nil {
     93 			return fmt.Errorf("line %d: #elif without #if", lineNo)
     94 		}
     95 		if top.elseSeen {
     96 			return fmt.Errorf("line %d: #elif after #else", lineNo)
     97 		}
     98 		result, err := evalCondition(strings.TrimSpace(directive[5:]), cfg)
     99 		if err != nil {
    100 			return fmt.Errorf("line %d: %w", lineNo, err)
    101 		}
    102 		pa := stack.parentActive()
    103 		top.active = pa && !top.seen && result
    104 		if result {
    105 			top.seen = true
    106 		}
    107 	case "endif":
    108 		if directive != "endif" {
    109 			return fmt.Errorf("line %d: malformed #endif directive", lineNo)
    110 		}
    111 		if stack.top() == nil {
    112 			return fmt.Errorf("line %d: #endif without #if", lineNo)
    113 		}
    114 		stack.pop()
    115 	}
    116 	return nil
    117 }
    118 
    119 // stripDirectiveComments removes c comments from a preprocessor line. open
    120 // reports a block comment that carries on past the end of the line
    121 func stripDirectiveComments(s string) (string, bool) {
    122 	var b strings.Builder
    123 	for {
    124 		block := strings.Index(s, "/*")
    125 		line := strings.Index(s, "//")
    126 		if line >= 0 && (block < 0 || line < block) {
    127 			b.WriteString(s[:line])
    128 			return strings.TrimSpace(b.String()), false
    129 		}
    130 		if block < 0 {
    131 			b.WriteString(s)
    132 			return strings.TrimSpace(b.String()), false
    133 		}
    134 		b.WriteString(s[:block])
    135 		end := strings.Index(s[block+2:], "*/")
    136 		if end < 0 {
    137 			return strings.TrimSpace(b.String()), true
    138 		}
    139 		b.WriteByte(' ')
    140 		s = s[block+2+end+2:]
    141 	}
    142 }
    143 
    144 func extractManLines(path string, cfg Config) ([]string, error) {
    145 	contentBytes, err := os.ReadFile(path)
    146 	if err != nil {
    147 		return nil, err
    148 	}
    149 
    150 	var lines []string
    151 	stack := &ifStack{}
    152 	sc := bufio.NewScanner(strings.NewReader(string(contentBytes)))
    153 	sc.Buffer(make([]byte, 1<<20), 1<<20)
    154 	inBlockComment := false
    155 	inDirectiveComment := false
    156 	pendingDirective := ""
    157 
    158 	lineNo := 0
    159 	for sc.Scan() {
    160 		lineNo++
    161 		line := sc.Text()
    162 		trimmed := strings.TrimSpace(line)
    163 
    164 		if inBlockComment {
    165 			if strings.Contains(trimmed, "*/") {
    166 				inBlockComment = false
    167 				idx := strings.Index(trimmed, "*/")
    168 				before := strings.TrimSpace(trimmed[:idx])
    169 				if strings.HasPrefix(before, "* ") {
    170 					before = before[2:]
    171 				} else if before == "*" {
    172 					before = ""
    173 				}
    174 				if before != "" {
    175 					lines = append(lines, stripManPrefix(before))
    176 				}
    177 				continue
    178 			}
    179 
    180 			stripped := trimmed
    181 			if strings.HasPrefix(stripped, "* ") {
    182 				stripped = stripped[2:]
    183 			} else if stripped == "*" {
    184 				stripped = ""
    185 			}
    186 			lines = append(lines, stripManPrefix(stripped))
    187 			continue
    188 		}
    189 
    190 		if inDirectiveComment || strings.HasPrefix(trimmed, "#") {
    191 			text := pendingDirective
    192 			if inDirectiveComment {
    193 				idx := strings.Index(trimmed, "*/")
    194 				if idx < 0 {
    195 					continue
    196 				}
    197 				text += " " + trimmed[idx+2:]
    198 				pendingDirective = ""
    199 				inDirectiveComment = false
    200 			} else {
    201 				text = trimmed[1:]
    202 			}
    203 			text, open := stripDirectiveComments(text)
    204 			if open {
    205 				inDirectiveComment = true
    206 				pendingDirective = text
    207 				continue
    208 			}
    209 
    210 			if err := parseConditional(text, cfg, stack, lineNo); err != nil {
    211 				return nil, err
    212 			}
    213 			continue
    214 		}
    215 
    216 		if !stack.globallyActive() {
    217 			continue
    218 		}
    219 
    220 		if strings.Contains(trimmed, "/* ?man") {
    221 			startIdx := strings.Index(trimmed, "/* ?man")
    222 			rest := strings.TrimSpace(trimmed[startIdx+7:])
    223 			if strings.HasSuffix(rest, " */") {
    224 				lines = append(lines, strings.TrimSpace(rest[:len(rest)-2]))
    225 			} else {
    226 				lines = append(lines, rest)
    227 				inBlockComment = true
    228 			}
    229 			continue
    230 		}
    231 
    232 		if idx := strings.Index(trimmed, "// ?man"); idx >= 0 {
    233 			lines = append(lines, strings.TrimSpace(trimmed[idx+7:]))
    234 		}
    235 	}
    236 
    237 	if err := sc.Err(); err != nil {
    238 		return nil, err
    239 	}
    240 	if inBlockComment {
    241 		return nil, fmt.Errorf("unterminated man comment")
    242 	}
    243 	if len(stack.frames) != 0 {
    244 		return nil, fmt.Errorf("unterminated preprocessor conditional")
    245 	}
    246 	return lines, nil
    247 }
    248 
    249 func stripManPrefix(line string) string {
    250 	if strings.HasPrefix(line, "// ?man ") {
    251 		return line[8:]
    252 	}
    253 	if strings.HasPrefix(line, "// ?man") {
    254 		return line[7:]
    255 	}
    256 	return line
    257 }
    258 
    259 func ParsePage(path string, cfg Config, section int, date string) (*Page, error) {
    260 	lines, err := extractManLines(path, cfg)
    261 	if err != nil {
    262 		return nil, err
    263 	}
    264 
    265 	page := &Page{Section: section, Date: date}
    266 
    267 	var descriptionLines []string
    268 	var sections []rawSection
    269 	var currentSection *rawSection
    270 	var sawContent bool
    271 	var fallbackArgs string
    272 	var rawOptions []rawOption
    273 	var currentOption *rawOption
    274 	optionNames := make(map[string]bool)
    275 
    276 	for _, raw := range lines {
    277 		line := strings.TrimSpace(raw)
    278 		if line == "" {
    279 			if currentSection != nil {
    280 				currentSection.Lines = append(currentSection.Lines, "")
    281 			} else if currentOption != nil {
    282 				currentOption.Lines = append(currentOption.Lines, "")
    283 			} else if sawContent {
    284 				descriptionLines = append(descriptionLines, "")
    285 			}
    286 			continue
    287 		}
    288 
    289 		if page.Name == "" && !strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "#") {
    290 			if name, summary, ok := parseNameSummary(line); ok {
    291 				if !manNamePattern.MatchString(name) || summary == "" {
    292 					return nil, fmt.Errorf("malformed command metadata %q", line)
    293 				}
    294 				page.Name = name
    295 				page.Summary = summary
    296 				sawContent = true
    297 				continue
    298 			}
    299 		}
    300 
    301 		lower := strings.ToLower(line)
    302 		if lower == "synopsis" || lower == "arguments" {
    303 			return nil, fmt.Errorf("invalid synopsis metadata %q", line)
    304 		}
    305 		switch {
    306 		case strings.HasPrefix(lower, "synopsis:"):
    307 			currentOption = nil
    308 			form := strings.TrimSpace(line[len("synopsis:"):])
    309 			if form != "" {
    310 				synopsis, err := parseSynopsis(form, true)
    311 				if err != nil {
    312 					return nil, fmt.Errorf("invalid synopsis metadata: %w", err)
    313 				}
    314 				page.Synopsis = append(page.Synopsis, synopsis)
    315 			}
    316 			sawContent = true
    317 			continue
    318 		case strings.HasPrefix(lower, "arguments:"):
    319 			currentOption = nil
    320 			fallbackArgs = strings.TrimSpace(line[len("arguments:"):])
    321 			if fallbackArgs == "" {
    322 				return nil, fmt.Errorf("invalid synopsis metadata: empty arguments")
    323 			}
    324 			sawContent = true
    325 			continue
    326 		case strings.HasPrefix(line, "## "):
    327 			currentOption = nil
    328 			title := strings.TrimSpace(line[3:])
    329 			sections = append(sections, rawSection{Title: title})
    330 			currentSection = &sections[len(sections)-1]
    331 			sawContent = true
    332 			continue
    333 		}
    334 
    335 		if currentSection == nil {
    336 			if strings.HasPrefix(line, "-") {
    337 				opt, err := parseOption(line)
    338 				if err != nil {
    339 					return nil, err
    340 				}
    341 				name := optionIdentity(opt)
    342 				if optionNames[name] {
    343 					return nil, fmt.Errorf("duplicate option %q", name)
    344 				}
    345 				optionNames[name] = true
    346 				rawOptions = append(rawOptions, rawOption{
    347 					Option: opt,
    348 					Lines:  []string{opt.Desc},
    349 				})
    350 				currentOption = &rawOptions[len(rawOptions)-1]
    351 			} else if isCodeLabel(line) || isCodeLabelPrefix(line) {
    352 				continue
    353 			} else if currentOption != nil {
    354 				currentOption.Lines = append(currentOption.Lines, line)
    355 			} else {
    356 				descriptionLines = append(descriptionLines, line)
    357 			}
    358 			sawContent = true
    359 			continue
    360 		}
    361 
    362 		currentSection.Lines = append(currentSection.Lines, line)
    363 		sawContent = true
    364 	}
    365 
    366 	if !sawContent {
    367 		return nil, nil
    368 	}
    369 	if page.Name == "" {
    370 		return nil, fmt.Errorf("first man comment must be NAME: SUMMARY")
    371 	}
    372 
    373 	groupMembers := make(map[string]int)
    374 	groupRequired := make(map[string]int)
    375 	for _, raw := range rawOptions {
    376 		option := raw.Option
    377 		if option.Group == "" {
    378 			continue
    379 		}
    380 		groupMembers[option.Group]++
    381 		required := 0
    382 		if option.Required {
    383 			required = 1
    384 		}
    385 		if groupRequired[option.Group] != 0 && groupRequired[option.Group] != required {
    386 			groupRequired[option.Group] = -1
    387 		} else if groupRequired[option.Group] == 0 {
    388 			groupRequired[option.Group] = required
    389 		}
    390 	}
    391 	for name, count := range groupMembers {
    392 		if count < 2 {
    393 			return nil, fmt.Errorf("mutual exclusion group %q has one option", name)
    394 		}
    395 		if groupRequired[name] < 0 {
    396 			return nil, fmt.Errorf("mutual exclusion group %q mixes required and optional options", name)
    397 		}
    398 	}
    399 
    400 	// explicit synopsis forms are authoritative. for simple pages we can produce
    401 	// a synopsis from the parsed option specs plus the arguments line
    402 	for _, raw := range rawOptions {
    403 		raw.Option.Body = parseBlocks(raw.Lines, "")
    404 		page.Options = append(page.Options, raw.Option)
    405 	}
    406 
    407 	if len(page.Synopsis) == 0 && fallbackArgs != "" {
    408 		synopsis, err := synthesizeSynopsis(page.Options, fallbackArgs)
    409 		if err != nil {
    410 			return nil, fmt.Errorf("invalid synopsis metadata: %w", err)
    411 		}
    412 		page.Synopsis = append(page.Synopsis, synopsis)
    413 	}
    414 
    415 	page.Description = parseBlocks(descriptionLines, "")
    416 	for _, section := range sections {
    417 		page.Sections = append(page.Sections, Section{
    418 			Title:  section.Title,
    419 			Blocks: parseBlocks(section.Lines, section.Title),
    420 		})
    421 	}
    422 	normalizePageInlines(page)
    423 
    424 	return page, nil
    425 }
    426 
    427 type rawSection struct {
    428 	Title string
    429 	Lines []string
    430 }
    431 
    432 type rawOption struct {
    433 	Option Option
    434 	Lines  []string
    435 }
    436 
    437 var optionFlagPattern = regexp.MustCompile(`^(?:--|--?[A-Za-z0-9?][A-Za-z0-9?-]*)$`)
    438 var optionTypePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]*$`)
    439 
    440 func parseOption(line string) (Option, error) {
    441 	parts := strings.Split(line, ":")
    442 	if len(parts) < 2 {
    443 		return Option{}, fmt.Errorf("malformed option %q: missing type separator", line)
    444 	}
    445 
    446 	if len(parts) > 2 && strings.TrimSpace(parts[1]) == "" {
    447 		return Option{}, fmt.Errorf("malformed option %q: empty type", line)
    448 	}
    449 
    450 	specParts := []string{strings.TrimSpace(parts[0])}
    451 	descriptionAt := 1
    452 	for descriptionAt < len(parts)-1 {
    453 		part := strings.TrimSpace(parts[descriptionAt])
    454 		if !looksLikeOptionArg(part) {
    455 			break
    456 		}
    457 		specParts = append(specParts, part)
    458 		descriptionAt++
    459 	}
    460 	if len(specParts) > 2 {
    461 		return Option{}, fmt.Errorf("malformed option %q: expected at most one type", line)
    462 	}
    463 
    464 	description := strings.TrimSpace(strings.Join(parts[descriptionAt:], ":"))
    465 	spec := strings.Join(specParts, ":")
    466 	flag, typ, group, required, err := splitOptionSpec(spec)
    467 	if err != nil {
    468 		return Option{}, fmt.Errorf("malformed option %q: %w", line, err)
    469 	}
    470 	if !optionFlagPattern.MatchString(flag) {
    471 		return Option{}, fmt.Errorf("malformed option %q: invalid flag", line)
    472 	}
    473 	if typ != "" && !optionTypePattern.MatchString(typ) {
    474 		return Option{}, fmt.Errorf("malformed option %q: invalid type %q", line, typ)
    475 	}
    476 
    477 	rawSpec := flag
    478 	if typ != "" {
    479 		rawSpec += " " + typ
    480 	}
    481 	normalized := normalizeOptionSpec(rawSpec)
    482 	description = stripRepeatedSpec(normalized, description)
    483 	if description == "" {
    484 		return Option{}, fmt.Errorf("malformed option %q: missing description", line)
    485 	}
    486 	items, err := parseSynopsis(normalized, false)
    487 	if err != nil {
    488 		return Option{}, fmt.Errorf("malformed option %q: %w", line, err)
    489 	}
    490 	if len(items.Items) == 0 {
    491 		return Option{}, fmt.Errorf("malformed option %q: empty synopsis", line)
    492 	}
    493 
    494 	return Option{
    495 		Spec:     items.Items,
    496 		Desc:     description,
    497 		Key:      synopsisKey(normalized) + "\x00" + group,
    498 		Group:    group,
    499 		Required: required,
    500 	}, nil
    501 }
    502 
    503 func splitOptionSpec(raw string) (flag, typ, group string, required bool, err error) {
    504 	raw = strings.TrimSpace(raw)
    505 	if strings.Count(raw, "!") > 1 {
    506 		return "", "", "", false, fmt.Errorf("duplicate required marker")
    507 	}
    508 	if strings.HasSuffix(raw, "!") {
    509 		required = true
    510 		raw = strings.TrimSpace(raw[:len(raw)-1])
    511 	} else if strings.Contains(raw, "!") {
    512 		return "", "", "", false, fmt.Errorf("misplaced required marker")
    513 	}
    514 
    515 	matches := groupPattern.FindAllStringIndex(raw, -1)
    516 	if strings.ContainsAny(raw, "{}") {
    517 		if len(matches) != 1 {
    518 			return "", "", "", false, fmt.Errorf("invalid mutual exclusion group")
    519 		}
    520 		start, end := matches[0][0], matches[0][1]
    521 		if start == 0 || (end != len(raw) && !strings.HasPrefix(raw[end:], ":")) {
    522 			return "", "", "", false, fmt.Errorf("misplaced mutual exclusion group")
    523 		}
    524 		group = raw[start+1 : end-1]
    525 		raw = raw[:start] + raw[end:]
    526 	}
    527 
    528 	if strings.Count(raw, ":") > 1 {
    529 		return "", "", "", false, fmt.Errorf("more than one type suffix")
    530 	}
    531 	if idx := strings.IndexByte(raw, ':'); idx >= 0 {
    532 		flag = strings.TrimSpace(raw[:idx])
    533 		typ = strings.TrimSpace(raw[idx+1:])
    534 	} else {
    535 		flag = strings.TrimSpace(raw)
    536 	}
    537 	return flag, typ, group, required, nil
    538 }
    539 
    540 func looksLikeOptionArg(s string) bool {
    541 	return s != "" && !strings.ContainsAny(s, " \t")
    542 }
    543 
    544 func normalizeOptionSpec(spec string) string {
    545 	spec = strings.TrimSpace(spec)
    546 	if spec == "" {
    547 		return ""
    548 	}
    549 
    550 	parts := strings.Split(spec, ":")
    551 	if len(parts) == 1 {
    552 		return strings.Join(strings.Fields(spec), " ")
    553 	}
    554 
    555 	normalized := []string{strings.TrimSpace(parts[0])}
    556 	for _, part := range parts[1:] {
    557 		part = strings.TrimSpace(part)
    558 		if part == "" {
    559 			continue
    560 		}
    561 		normalized = append(normalized, part)
    562 	}
    563 	return strings.Join(normalized, " ")
    564 }
    565 
    566 func stripRepeatedSpec(spec, desc string) string {
    567 	spec = strings.TrimSpace(spec)
    568 	desc = strings.TrimSpace(desc)
    569 	candidates := []string{
    570 		spec + ":",
    571 		strings.ReplaceAll(spec, " ", ":") + ":",
    572 	}
    573 	for _, candidate := range candidates {
    574 		if strings.HasPrefix(desc, candidate) {
    575 			return strings.TrimSpace(desc[len(candidate):])
    576 		}
    577 	}
    578 	return desc
    579 }
    580 
    581 func optionIdentity(opt Option) string {
    582 	parts := make([]string, 0, len(opt.Spec))
    583 	for _, item := range opt.Spec {
    584 		if item.Kind == SynFlag {
    585 			parts = append(parts, item.Text)
    586 		}
    587 	}
    588 	return strings.Join(parts, "\x00")
    589 }
    590 
    591 func optionPrimaryFlag(opt Option) string {
    592 	for _, item := range opt.Spec {
    593 		if item.Kind == SynFlag {
    594 			return item.Text
    595 		}
    596 	}
    597 	return ""
    598 }
    599 
    600 func synopsisKey(spec string) string {
    601 	return strings.Join(strings.Fields(spec), " ")
    602 }
    603 
    604 func isCodeLabel(line string) bool {
    605 	if !strings.HasSuffix(line, ":") {
    606 		return false
    607 	}
    608 	for _, r := range line[:len(line)-1] {
    609 		if (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' {
    610 			return false
    611 		}
    612 	}
    613 	return len(line) > 1
    614 }
    615 
    616 func isCodeLabelPrefix(line string) bool {
    617 	idx := strings.IndexByte(line, ':')
    618 	if idx <= 0 {
    619 		return false
    620 	}
    621 	return isCodeLabel(line[:idx+1])
    622 }
    623 
    624 func parseBlocks(lines []string, title string) []Block {
    625 	lines = trimBlankLines(lines)
    626 	if len(lines) == 0 {
    627 		return nil
    628 	}
    629 
    630 	if blocks, ok := parseSubsections(lines, title); ok {
    631 		return blocks
    632 	}
    633 
    634 	if items, ok := parseHeadingItems(lines); ok {
    635 		return []Block{{Kind: BlockTaggedList, Items: items}}
    636 	}
    637 
    638 	if items, ok := parseSequentialTaggedItems(lines); ok {
    639 		return []Block{{Kind: BlockTaggedList, Items: items}}
    640 	}
    641 
    642 	paragraphs := splitParagraphs(lines)
    643 	var blocks []Block
    644 
    645 	for _, paragraph := range paragraphs {
    646 		if len(paragraph) == 0 {
    647 			continue
    648 		}
    649 
    650 		if isSeeAlsoTitle(title) {
    651 			if refs, ok := parseXRefs(strings.Join(paragraph, " ")); ok {
    652 				slices.SortFunc(refs, func(a, b XRef) int {
    653 					if a.Section != b.Section {
    654 						return strings.Compare(a.Section, b.Section)
    655 					}
    656 					return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
    657 				})
    658 				blocks = append(blocks, Block{Kind: BlockSeeAlso, Refs: refs})
    659 				continue
    660 			}
    661 		}
    662 
    663 		if item, ok := parseTaggedItem(paragraph); ok {
    664 			if len(blocks) != 0 && blocks[len(blocks)-1].Kind == BlockTaggedList {
    665 				blocks[len(blocks)-1].Items = append(blocks[len(blocks)-1].Items, item)
    666 			} else {
    667 				blocks = append(blocks, Block{Kind: BlockTaggedList, Items: []Item{item}})
    668 			}
    669 			continue
    670 		}
    671 
    672 		blocks = append(blocks, Block{
    673 			Kind:    BlockParagraph,
    674 			Inlines: parseInlines(strings.Join(paragraph, " ")),
    675 		})
    676 	}
    677 
    678 	return blocks
    679 }
    680 
    681 func parseSubsections(lines []string, title string) ([]Block, bool) {
    682 	hasHeading := false
    683 	for _, line := range lines {
    684 		if strings.HasPrefix(strings.TrimSpace(line), "### ") {
    685 			hasHeading = true
    686 			break
    687 		}
    688 	}
    689 	if !hasHeading {
    690 		return nil, false
    691 	}
    692 
    693 	var blocks []Block
    694 	var preamble []string
    695 	for len(lines) != 0 && !strings.HasPrefix(strings.TrimSpace(lines[0]), "### ") {
    696 		preamble = append(preamble, lines[0])
    697 		lines = lines[1:]
    698 	}
    699 	if parsed := parseBlocks(preamble, title); len(parsed) != 0 {
    700 		blocks = append(blocks, parsed...)
    701 	}
    702 
    703 	for len(lines) != 0 {
    704 		head := strings.TrimSpace(lines[0])
    705 		if !strings.HasPrefix(head, "### ") {
    706 			return nil, false
    707 		}
    708 		subtitle := strings.TrimSpace(head[4:])
    709 		lines = lines[1:]
    710 		var body []string
    711 		for len(lines) != 0 && !strings.HasPrefix(strings.TrimSpace(lines[0]), "### ") {
    712 			body = append(body, lines[0])
    713 			lines = lines[1:]
    714 		}
    715 		blocks = append(blocks, Block{
    716 			Kind:   BlockSubsection,
    717 			Title:  subtitle,
    718 			Blocks: parseBlocks(body, subtitle),
    719 		})
    720 	}
    721 
    722 	return blocks, true
    723 }
    724 
    725 func trimBlankLines(lines []string) []string {
    726 	start := 0
    727 	for start < len(lines) && strings.TrimSpace(lines[start]) == "" {
    728 		start++
    729 	}
    730 	end := len(lines)
    731 	for end > start && strings.TrimSpace(lines[end-1]) == "" {
    732 		end--
    733 	}
    734 	return lines[start:end]
    735 }
    736 
    737 func splitParagraphs(lines []string) [][]string {
    738 	var paragraphs [][]string
    739 	var current []string
    740 	for _, line := range lines {
    741 		if strings.TrimSpace(line) == "" {
    742 			if len(current) != 0 {
    743 				paragraphs = append(paragraphs, current)
    744 				current = nil
    745 			}
    746 			continue
    747 		}
    748 		current = append(current, line)
    749 	}
    750 	if len(current) != 0 {
    751 		paragraphs = append(paragraphs, current)
    752 	}
    753 	return paragraphs
    754 }
    755 
    756 func parseHeadingItems(lines []string) ([]Item, bool) {
    757 	var items []Item
    758 	var current *Item
    759 	for _, line := range lines {
    760 		if strings.TrimSpace(line) == "" {
    761 			continue
    762 		}
    763 		if strings.HasPrefix(line, "### ") {
    764 			items = append(items, Item{Label: parseInlines(strings.TrimSpace(line[4:]))})
    765 			current = &items[len(items)-1]
    766 			continue
    767 		}
    768 		if current == nil {
    769 			return nil, false
    770 		}
    771 		if len(current.Body) != 0 {
    772 			current.Body = append(current.Body, Inline{Kind: InlineText, Text: " "})
    773 		}
    774 		current.Body = append(current.Body, parseInlines(strings.TrimSpace(line))...)
    775 	}
    776 	return items, len(items) != 0
    777 }
    778 
    779 func parseSequentialTaggedItems(lines []string) ([]Item, bool) {
    780 	var items []Item
    781 	for i := 0; i < len(lines); {
    782 		for i < len(lines) && strings.TrimSpace(lines[i]) == "" {
    783 			i++
    784 		}
    785 		if i >= len(lines) {
    786 			break
    787 		}
    788 
    789 		label := strings.TrimSpace(lines[i])
    790 		if label == "" || i+1 >= len(lines) {
    791 			return nil, false
    792 		}
    793 		first := strings.TrimSpace(lines[i+1])
    794 		if !strings.HasPrefix(first, ":") {
    795 			return nil, false
    796 		}
    797 
    798 		bodyLines := []string{strings.TrimSpace(strings.TrimPrefix(first, ":"))}
    799 		i += 2
    800 		for i < len(lines) {
    801 			line := strings.TrimSpace(lines[i])
    802 			if line == "" {
    803 				i++
    804 				break
    805 			}
    806 			if i+1 < len(lines) && strings.TrimSpace(lines[i]) != "" &&
    807 				strings.HasPrefix(strings.TrimSpace(lines[i+1]), ":") {
    808 				break
    809 			}
    810 			bodyLines = append(bodyLines, line)
    811 			i++
    812 		}
    813 
    814 		items = append(items, Item{
    815 			Label: parseInlines(label),
    816 			Body:  parseInlines(strings.Join(compactLines(bodyLines), " ")),
    817 		})
    818 	}
    819 	return items, len(items) != 0
    820 }
    821 
    822 func parseTaggedItem(lines []string) (Item, bool) {
    823 	if len(lines) < 2 {
    824 		return Item{}, false
    825 	}
    826 	label := strings.TrimSpace(lines[0])
    827 	bodyLines := lines[1:]
    828 	if label == "" {
    829 		return Item{}, false
    830 	}
    831 
    832 	first := strings.TrimSpace(bodyLines[0])
    833 	if !strings.HasPrefix(first, ":") {
    834 		return Item{}, false
    835 	}
    836 
    837 	bodyLines[0] = strings.TrimSpace(strings.TrimPrefix(first, ":"))
    838 	return Item{
    839 		Label: parseInlines(label),
    840 		Body:  parseInlines(strings.Join(compactLines(bodyLines), " ")),
    841 	}, true
    842 }
    843 
    844 func parseInlines(s string) []Inline {
    845 	var out []Inline
    846 	var text strings.Builder
    847 	flushText := func() {
    848 		if text.Len() == 0 {
    849 			return
    850 		}
    851 		out = append(out, Inline{Kind: InlineText, Text: text.String()})
    852 		text.Reset()
    853 	}
    854 
    855 	// inline semantics are parsed here so the renderer never has to recover
    856 	// any richness like paths, flags, emphasis, or xrefs by reparsing raw strings
    857 	for i := 0; i < len(s); {
    858 		switch s[i] {
    859 		case '`':
    860 			end := strings.IndexByte(s[i+1:], '`')
    861 			if end < 0 {
    862 				text.WriteByte(s[i])
    863 				i++
    864 				continue
    865 			}
    866 			end += i + 1
    867 			flushText()
    868 			out = append(out, classifyInlineLiteral(s[i+1:end]))
    869 			i = end + 1
    870 		case '_':
    871 			end := strings.IndexByte(s[i+1:], '_')
    872 			if end < 0 {
    873 				text.WriteByte(s[i])
    874 				i++
    875 				continue
    876 			}
    877 			end += i + 1
    878 			flushText()
    879 			out = append(out, Inline{
    880 				Kind:     InlineEmph,
    881 				Children: parseInlines(s[i+1 : end]),
    882 			})
    883 			i = end + 1
    884 		default:
    885 			text.WriteByte(s[i])
    886 			i++
    887 		}
    888 	}
    889 
    890 	flushText()
    891 	return out
    892 }
    893 
    894 func classifyInlineLiteral(s string) Inline {
    895 	s = strings.TrimSpace(s)
    896 	if match := xrefPattern.FindStringSubmatch(s); match != nil {
    897 		return Inline{Kind: InlineXRef, Text: match[1], Section: match[2]}
    898 	}
    899 	if strings.HasPrefix(s, "/") {
    900 		return Inline{Kind: InlinePath, Text: s}
    901 	}
    902 	if strings.HasPrefix(s, "-") {
    903 		return Inline{Kind: InlineFlag, Text: strings.TrimPrefix(s, "-")}
    904 	}
    905 	return Inline{Kind: InlineLiteral, Text: s}
    906 }
    907 
    908 func synthesizeSynopsis(options []Option, args string) (SynopsisForm, error) {
    909 	type unit struct {
    910 		sortKey string
    911 		items   []SynopsisItem
    912 	}
    913 
    914 	groups := make(map[string][]Option)
    915 	var groupOrder []string
    916 	var units []unit
    917 
    918 	for _, opt := range options {
    919 		if opt.Group == "" {
    920 			if opt.Required {
    921 				units = append(units, unit{
    922 					sortKey: optionSortKey(opt),
    923 					items:   cloneSynopsisItems(opt.Spec),
    924 				})
    925 			} else {
    926 				units = append(units, unit{
    927 					sortKey: optionSortKey(opt),
    928 					items: []SynopsisItem{{
    929 						Kind:     SynOptional,
    930 						Children: cloneSynopsisItems(opt.Spec),
    931 					}},
    932 				})
    933 			}
    934 			continue
    935 		}
    936 		if _, seen := groups[opt.Group]; !seen {
    937 			groupOrder = append(groupOrder, opt.Group)
    938 		}
    939 		groups[opt.Group] = append(groups[opt.Group], opt)
    940 	}
    941 
    942 	for _, name := range groupOrder {
    943 		members := groups[name]
    944 		required := false
    945 		for _, m := range members {
    946 			if m.Required {
    947 				required = true
    948 				break
    949 			}
    950 		}
    951 
    952 		var children []SynopsisItem
    953 		for i, m := range members {
    954 			if i != 0 {
    955 				children = append(children, SynopsisItem{Kind: SynPipe, Text: "|"})
    956 			}
    957 			children = append(children, cloneSynopsisItems(m.Spec)...)
    958 		}
    959 
    960 		kind := SynOptional
    961 		if required {
    962 			kind = SynRequiredGroup
    963 		}
    964 		units = append(units, unit{
    965 			sortKey: optionSortKey(members[0]),
    966 			items:   []SynopsisItem{{Kind: kind, Children: children}},
    967 		})
    968 	}
    969 
    970 	slices.SortFunc(units, func(a, b unit) int {
    971 		return strings.Compare(a.sortKey, b.sortKey)
    972 	})
    973 
    974 	var items []SynopsisItem
    975 	for _, u := range units {
    976 		items = append(items, u.items...)
    977 	}
    978 	argsSynopsis, err := parseSynopsis(args, false)
    979 	if err != nil {
    980 		return SynopsisForm{}, err
    981 	}
    982 	items = append(items, argsSynopsis.Items...)
    983 	return SynopsisForm{Items: items}, nil
    984 }
    985 
    986 func optionSortKey(opt Option) string {
    987 	flag := optionPrimaryFlag(opt)
    988 	if flag == "" {
    989 		return "zzzz"
    990 	}
    991 	r := flag[0]
    992 	prefix := "2"
    993 	switch {
    994 	case r >= '0' && r <= '9':
    995 		prefix = "0"
    996 	case r >= 'A' && r <= 'Z':
    997 		prefix = "1"
    998 	}
    999 	return prefix + flag
   1000 }
   1001 
   1002 func cloneSynopsisItems(items []SynopsisItem) []SynopsisItem {
   1003 	out := make([]SynopsisItem, len(items))
   1004 	for i, item := range items {
   1005 		out[i] = item
   1006 		if len(item.Children) != 0 {
   1007 			out[i].Children = cloneSynopsisItems(item.Children)
   1008 		}
   1009 	}
   1010 	return out
   1011 }
   1012 
   1013 func compactLines(lines []string) []string {
   1014 	var out []string
   1015 	for _, line := range lines {
   1016 		line = strings.TrimSpace(line)
   1017 		if line != "" {
   1018 			out = append(out, line)
   1019 		}
   1020 	}
   1021 	return out
   1022 }
   1023 
   1024 func isSeeAlsoTitle(title string) bool {
   1025 	return strings.EqualFold(strings.TrimSpace(title), "SEE ALSO")
   1026 }
   1027 
   1028 func parseXRefs(s string) ([]XRef, bool) {
   1029 	var refs []XRef
   1030 	for _, part := range strings.Split(s, ",") {
   1031 		part = strings.TrimSpace(part)
   1032 		match := xrefPattern.FindStringSubmatch(part)
   1033 		if match == nil {
   1034 			return nil, false
   1035 		}
   1036 		refs = append(refs, XRef{Name: match[1], Section: match[2]})
   1037 	}
   1038 	return refs, len(refs) != 0
   1039 }
   1040 
   1041 func parseSynopsis(raw string, explicit bool) (SynopsisForm, error) {
   1042 	tokens := tokenizeSynopsis(raw)
   1043 	if len(tokens) == 0 {
   1044 		return SynopsisForm{}, nil
   1045 	}
   1046 	items, next, closer, err := parseSynopsisSeq(tokens, 0, explicit, true)
   1047 	if err != nil {
   1048 		return SynopsisForm{}, err
   1049 	}
   1050 	if closer != "" {
   1051 		return SynopsisForm{}, fmt.Errorf("unexpected %q", closer)
   1052 	}
   1053 	if next != len(tokens) {
   1054 		return SynopsisForm{}, fmt.Errorf("unclosed %q", tokens[next])
   1055 	}
   1056 	return SynopsisForm{Items: items}, nil
   1057 }
   1058 
   1059 func tokenizeSynopsis(raw string) []string {
   1060 	var tokens []string
   1061 	var current strings.Builder
   1062 	flush := func() {
   1063 		if current.Len() != 0 {
   1064 			tokens = append(tokens, current.String())
   1065 			current.Reset()
   1066 		}
   1067 	}
   1068 
   1069 	for i := 0; i < len(raw); i++ {
   1070 		ch := raw[i]
   1071 		switch ch {
   1072 		case '[', ']', '{', '}', '|':
   1073 			flush()
   1074 			tokens = append(tokens, string(ch))
   1075 		case ' ', '\t', '\n':
   1076 			flush()
   1077 		default:
   1078 			current.WriteByte(ch)
   1079 		}
   1080 	}
   1081 	flush()
   1082 	return tokens
   1083 }
   1084 
   1085 func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) ([]SynopsisItem, int, string, error) {
   1086 	var items []SynopsisItem
   1087 	seenNonFlag := false
   1088 
   1089 	for i := start; i < len(tokens); i++ {
   1090 		switch tokens[i] {
   1091 		case "]", "}":
   1092 			if len(items) == 0 {
   1093 				return nil, i, tokens[i], fmt.Errorf("empty group")
   1094 			}
   1095 			return items, i, tokens[i], nil
   1096 		case "[", "{":
   1097 			open := tokens[i]
   1098 			children, next, closer, err := parseSynopsisSeq(tokens, i+1, explicit, false)
   1099 			if err != nil {
   1100 				return nil, next, closer, err
   1101 			}
   1102 			if closer == "" {
   1103 				return nil, next, closer, fmt.Errorf("unclosed %q", open)
   1104 			}
   1105 			expected := "]"
   1106 			kind := SynOptional
   1107 			if open == "{" {
   1108 				expected = "}"
   1109 				kind = SynRequiredGroup
   1110 			}
   1111 			if closer != expected {
   1112 				return nil, next, closer, fmt.Errorf("mismatched %q and %q", open, closer)
   1113 			}
   1114 			items = append(items, SynopsisItem{Kind: kind, Children: children})
   1115 			i = next
   1116 		case "|":
   1117 			if i+1 >= len(tokens) || tokens[i+1] == "|" || tokens[i+1] == "]" || tokens[i+1] == "}" {
   1118 				return nil, i, "", fmt.Errorf("misplaced |")
   1119 			}
   1120 			if i != start {
   1121 				previous := tokens[i-1]
   1122 				if previous == "|" || previous == "[" || previous == "{" {
   1123 					return nil, i, "", fmt.Errorf("misplaced |")
   1124 				}
   1125 			} else if !topLevel {
   1126 				return nil, i, "", fmt.Errorf("misplaced |")
   1127 			}
   1128 			items = append(items, SynopsisItem{Kind: SynPipe, Text: "|"})
   1129 		default:
   1130 			if err := validateSynopsisToken(tokens[i]); err != nil {
   1131 				return nil, i, "", err
   1132 			}
   1133 			if flags, ok := splitGroupedFlags(tokens[i]); ok {
   1134 				items = append(items, flags...)
   1135 				continue
   1136 			}
   1137 			kind := classifySynopsisToken(tokens, i, explicit, topLevel, seenNonFlag)
   1138 			if tokens[i] == "..." {
   1139 				if len(items) == 0 {
   1140 					return nil, i, "", fmt.Errorf("misplaced ...")
   1141 				}
   1142 				items[len(items)-1].Text += " ..."
   1143 				continue
   1144 			}
   1145 			items = append(items, SynopsisItem{Kind: kind, Text: tokens[i]})
   1146 			if kind != SynFlag && kind != SynPipe {
   1147 				seenNonFlag = true
   1148 			}
   1149 		}
   1150 	}
   1151 
   1152 	return items, len(tokens), "", nil
   1153 }
   1154 
   1155 func validateSynopsisToken(token string) error {
   1156 	if strings.HasPrefix(token, "<") && (!strings.HasSuffix(token, ">") || token == "<>") {
   1157 		return fmt.Errorf("malformed angle placeholder %q", token)
   1158 	}
   1159 	if strings.HasSuffix(token, ">") && !strings.HasPrefix(token, "<") {
   1160 		return fmt.Errorf("malformed angle placeholder %q", token)
   1161 	}
   1162 	return nil
   1163 }
   1164 
   1165 func splitGroupedFlags(tok string) ([]SynopsisItem, bool) {
   1166 	// we expand compacted synopsis tokens like some -abcdef into separate
   1167 	// semantic flags so the renderer can emit a separate fl for each one
   1168 	if len(tok) < 3 || tok[0] != '-' {
   1169 		return nil, false
   1170 	}
   1171 	for i := 1; i < len(tok); i++ {
   1172 		c := tok[i]
   1173 		if (c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') {
   1174 			return nil, false
   1175 		}
   1176 	}
   1177 
   1178 	items := make([]SynopsisItem, 0, len(tok)-1)
   1179 	for i := 1; i < len(tok); i++ {
   1180 		items = append(items, SynopsisItem{
   1181 			Kind: SynFlag,
   1182 			Text: "-" + string(tok[i]),
   1183 		})
   1184 	}
   1185 	return items, true
   1186 }
   1187 
   1188 func classifySynopsisToken(tokens []string, i int, explicit, topLevel, seenNonFlag bool) SynopsisItemKind {
   1189 	tok := tokens[i]
   1190 	if strings.HasPrefix(tok, "-") {
   1191 		return SynFlag
   1192 	}
   1193 	if strings.HasPrefix(tok, "<") && strings.HasSuffix(tok, ">") {
   1194 		return SynArg
   1195 	}
   1196 	if strings.Contains(tok, "...") || strings.ContainsAny(tok, "/=:") {
   1197 		return SynArg
   1198 	}
   1199 	if i > 0 && tokens[i-1] == "|" {
   1200 		if explicit {
   1201 			return SynCommand
   1202 		}
   1203 		return SynArg
   1204 	}
   1205 	if i+1 < len(tokens) && tokens[i+1] == "|" {
   1206 		if explicit {
   1207 			return SynCommand
   1208 		}
   1209 		return SynArg
   1210 	}
   1211 	if i > 0 && strings.HasPrefix(tokens[i-1], "-") {
   1212 		return SynArg
   1213 	}
   1214 	if explicit && topLevel && !seenNonFlag && i+1 < len(tokens) && tokens[i+1] == "[" {
   1215 		return SynCommand
   1216 	}
   1217 	return SynArg
   1218 }
   1219 
   1220 func (p *Page) validate() error {
   1221 	if p.Name == "" {
   1222 		return fmt.Errorf("missing manpage name")
   1223 	}
   1224 	if p.Summary == "" {
   1225 		return fmt.Errorf("missing manpage summary")
   1226 	}
   1227 	return nil
   1228 }
   1229 
   1230 func normalizePageInlines(page *Page) {
   1231 	for i := range page.Description {
   1232 		page.Description[i] = mergeAdjacentTextInBlock(page.Description[i])
   1233 	}
   1234 	for i := range page.Options {
   1235 		for j := range page.Options[i].Body {
   1236 			page.Options[i].Body[j] = mergeAdjacentTextInBlock(page.Options[i].Body[j])
   1237 		}
   1238 	}
   1239 	for i := range page.Sections {
   1240 		for j := range page.Sections[i].Blocks {
   1241 			page.Sections[i].Blocks[j] = mergeAdjacentTextInBlock(page.Sections[i].Blocks[j])
   1242 		}
   1243 	}
   1244 }
   1245 
   1246 func mergeAdjacentTextInBlock(block Block) Block {
   1247 	block.Inlines = mergeAdjacentText(block.Inlines)
   1248 	for i := range block.Items {
   1249 		block.Items[i].Label = mergeAdjacentText(block.Items[i].Label)
   1250 		block.Items[i].Body = mergeAdjacentText(block.Items[i].Body)
   1251 	}
   1252 	return block
   1253 }
   1254 
   1255 func mergeAdjacentText(inlines []Inline) []Inline {
   1256 	if len(inlines) == 0 {
   1257 		return nil
   1258 	}
   1259 	out := []Inline{inlines[0]}
   1260 	for _, inline := range inlines[1:] {
   1261 		last := &out[len(out)-1]
   1262 		if last.Kind == InlineText && inline.Kind == InlineText {
   1263 			last.Text += inline.Text
   1264 			continue
   1265 		}
   1266 		out = append(out, inline)
   1267 	}
   1268 	return out
   1269 }