package main import ( "fmt" "os" "path/filepath" "regexp" "sort" "strings" ) // RefPage is one page of the API reference: a library (or the core // functions), drawn from its api.json section and its reference/.md. type RefPage struct { ID string Title string Desc string Load string // the requirelib() line, empty for built-in functions Order int Section *Section // nil for a library that only has a Markdown page Intro string // Markdown above the first heading Leading []*Function Blocks []*Block } // Block is a heading of a reference page and the Markdown below it, up to // the next heading of any level. type Block struct { Level int Heading string // the heading text, Markdown Body string // Set when the heading names functions, e.g. "`filelib.readFile(vpath)`". IsFn bool Sigs []sigSpan Ret string // what follows "→" in the heading Badges []string // the rest of the heading, e.g. "admin only" Entries []*Function After []*Function // api.json entries without a heading, placed after this block } type sigSpan struct { Name string // filelib.readFile Sig string // filelib.readFile(vpath) } // Names lists the identifiers the heading names. func (b *Block) Names() []string { out := make([]string, len(b.Sigs)) for i, s := range b.Sigs { out[i] = s.Name } return out } var ( headingRe = regexp.MustCompile(`^(#{1,6})\s+(.*?)\s*#*\s*$`) fenceRe = regexp.MustCompile("^ {0,3}(```|~~~)") spanRe = regexp.MustCompile("`([^`]+)`") sigRe = regexp.MustCompile(`^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*(\(.*\))?$`) ) // splitBlocks cuts Markdown at every heading outside fenced code. func splitBlocks(md string) (string, []*Block) { var intro strings.Builder var blocks []*Block var cur *Block var body strings.Builder inFence := false flush := func() { if cur != nil { cur.Body = strings.Trim(body.String(), "\n") blocks = append(blocks, cur) } else { intro.WriteString(body.String()) } body.Reset() } for _, line := range strings.Split(md, "\n") { if fenceRe.MatchString(line) { inFence = !inFence } if !inFence { if m := headingRe.FindStringSubmatch(line); m != nil { flush() cur = &Block{Level: len(m[1]), Heading: m[2]} continue } } body.WriteString(line) body.WriteByte('\n') } flush() return strings.Trim(intro.String(), "\n"), blocks } // parseHeading recognises function headings: one or more backticked // signatures, optionally separated by " / ", optionally followed by // "→ returns" and a remark such as "(admin only)". func parseHeading(b *Block, known map[string]bool) { // "Pattern 2 — `available()` polling" mentions a function but is about // something else: a function heading starts with the signature. if !strings.HasPrefix(strings.TrimSpace(b.Heading), "`") { return } left, right, hasRet := strings.Cut(b.Heading, "→") for _, m := range spanRe.FindAllStringSubmatch(left, -1) { inner := strings.TrimSpace(m[1]) sm := sigRe.FindStringSubmatch(inner) if sm == nil { continue } if sm[2] == "" && !known[sm[1]] { continue // a bare word in backticks, not a call } b.Sigs = append(b.Sigs, sigSpan{Name: sm[1], Sig: inner}) } if len(b.Sigs) == 0 { return } b.IsFn = true if hasRet { b.Ret = strings.TrimSpace(strings.ReplaceAll(right, "`", "")) } rest := spanRe.ReplaceAllString(left, "") rest = strings.Trim(strings.ReplaceAll(rest, "/", " "), " ") rest = strings.TrimSpace(rest) if rest != "" { b.Badges = append(b.Badges, strings.Trim(rest, "()")) } } // loadReferences reads reference/*.md and pairs each page with its api.json // section. Sections without a page still get one, drawn from api.json alone. func loadReferences(dir string, api *API, rep *report) ([]*RefPage, error) { files, err := filepath.Glob(filepath.Join(dir, "*.md")) if err != nil { return nil, err } byID := map[string]*Section{} for _, s := range api.Sections { byID[s.ID] = s } used := map[string]bool{} var pages []*RefPage for _, f := range files { raw, err := os.ReadFile(f) if err != nil { return nil, err } fm, body, err := splitFrontMatter(string(raw)) if err != nil { return nil, fmt.Errorf("%s: %w", f, err) } id := strings.TrimSuffix(filepath.Base(f), ".md") p := &RefPage{ID: id, Title: fm["title"], Desc: fm["summary"], Load: fm["load"], Order: atoiDefault(fm["order"], 1000)} if sid := fm["section"]; sid != "" { s, ok := byID[sid] if !ok { return nil, fmt.Errorf("%s: section %q is not in api.json", f, sid) } if used[sid] { return nil, fmt.Errorf("%s: section %q already has a page", f, sid) } used[sid] = true p.Section = s } else { rep.pageOnly = append(rep.pageOnly, id) } p.Intro, p.Blocks = splitBlocks(body) pages = append(pages, p) } for i, s := range api.Sections { if !used[s.ID] { rep.noPage = append(rep.noPage, s.ID) pages = append(pages, &RefPage{ID: s.ID, Order: 5000 + i, Section: s}) } } for _, p := range pages { p.fill() p.match(rep) } sort.SliceStable(pages, func(i, j int) bool { return pages[i].Order < pages[j].Order }) return pages, nil } // fill takes the title, summary and load line from api.json where the page // does not set its own. func (p *RefPage) fill() { if s := p.Section; s != nil { if p.Title == "" { p.Title = s.Name } if p.Desc == "" { p.Desc = s.Desc } if p.Load == "" { p.Load = s.Load } } if p.Title == "" { p.Title = p.ID } } // match pairs function headings with api.json entries. An entry without a // heading of its own is placed right after the block of the entry before it // in api.json, so related functions stay together. func (p *RefPage) match(rep *report) { known := map[string]bool{} var fns []*Function if p.Section != nil { fns = p.Section.Functions } for _, f := range fns { for _, n := range f.Names() { known[n] = true } } owner := map[*Function]*Block{} for _, b := range p.Blocks { parseHeading(b, known) if !b.IsFn { continue } names := map[string]bool{} for _, n := range b.Names() { names[n] = true } for _, f := range fns { if owner[f] != nil { continue } for _, n := range f.Names() { if names[n] { owner[f] = b b.Entries = append(b.Entries, f) break } } } if len(b.Entries) == 0 { for _, n := range b.Names() { rep.missingInAPI = append(rep.missingInAPI, p.ID+": "+n) } } } var last *Block for _, f := range fns { if b := owner[f]; b != nil { last = b continue } rep.noHeading = append(rep.noHeading, f.Name) // Prefer the block whose text introduces the function, such as a // list of related calls under "History actions". if b := p.mentioning(f); b != nil { b.After = append(b.After, f) continue } if last == nil { p.Leading = append(p.Leading, f) } else { last.After = append(last.After, f) } } } // mentioning returns the first block whose Markdown names one of f's // identifiers as a call in code (`name(`), if any. func (p *RefPage) mentioning(f *Function) *Block { for _, b := range p.Blocks { for _, n := range f.Names() { if strings.Contains(b.Body, "`"+n+"(") { return b } } } return nil } // AllFunctions lists what the page documents, api.json entries first, for // the function index, the search and the playground catalogue. type FnInfo struct { Names []string `json:"names"` Sig string `json:"sig"` Ret string `json:"ret,omitempty"` Desc string `json:"desc,omitempty"` Example string `json:"example,omitempty"` Anchor string `json:"-"` } func (p *RefPage) AllFunctions() []FnInfo { var out []FnInfo add := func(f *Function) { out = append(out, FnInfo{Names: f.Names(), Sig: f.Sig, Ret: f.Ret, Desc: f.Desc, Example: f.Example, Anchor: anchorFor(f.Names())}) } for _, f := range p.Leading { add(f) } for _, b := range p.Blocks { if b.IsFn { if len(b.Entries) == 0 { sigs := make([]string, len(b.Sigs)) for i, s := range b.Sigs { sigs[i] = s.Sig } out = append(out, FnInfo{Names: b.Names(), Sig: strings.Join(sigs, " / "), Ret: b.Ret, Desc: firstSentence(b.Body), Anchor: anchorFor(b.Names())}) } for _, f := range b.Entries { add(f) } } for _, f := range b.After { add(f) } } return out } // anchorFor is the element id of a function card: its first name. func anchorFor(names []string) string { if len(names) == 0 { return "" } return names[0] } var mdNoiseRe = regexp.MustCompile("`|\\*\\*|\\[([^\\]]*)\\]\\([^)]*\\)") // firstSentence is a plain-text summary of a Markdown body. func firstSentence(md string) string { for _, para := range strings.Split(md, "\n\n") { para = strings.TrimSpace(para) if para == "" || strings.HasPrefix(para, "```") || strings.HasPrefix(para, "|") || strings.HasPrefix(para, ">") { continue } para = strings.Join(strings.Fields(para), " ") para = mdNoiseRe.ReplaceAllString(para, "$1") if i := strings.Index(para, ". "); i > 0 { para = para[:i+1] } return para } return "" }