| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346 |
- 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/<id>.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 ""
- }
|