reference.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "regexp"
  7. "sort"
  8. "strings"
  9. )
  10. // RefPage is one page of the API reference: a library (or the core
  11. // functions), drawn from its api.json section and its reference/<id>.md.
  12. type RefPage struct {
  13. ID string
  14. Title string
  15. Desc string
  16. Load string // the requirelib() line, empty for built-in functions
  17. Order int
  18. Section *Section // nil for a library that only has a Markdown page
  19. Intro string // Markdown above the first heading
  20. Leading []*Function
  21. Blocks []*Block
  22. }
  23. // Block is a heading of a reference page and the Markdown below it, up to
  24. // the next heading of any level.
  25. type Block struct {
  26. Level int
  27. Heading string // the heading text, Markdown
  28. Body string
  29. // Set when the heading names functions, e.g. "`filelib.readFile(vpath)`".
  30. IsFn bool
  31. Sigs []sigSpan
  32. Ret string // what follows "→" in the heading
  33. Badges []string // the rest of the heading, e.g. "admin only"
  34. Entries []*Function
  35. After []*Function // api.json entries without a heading, placed after this block
  36. }
  37. type sigSpan struct {
  38. Name string // filelib.readFile
  39. Sig string // filelib.readFile(vpath)
  40. }
  41. // Names lists the identifiers the heading names.
  42. func (b *Block) Names() []string {
  43. out := make([]string, len(b.Sigs))
  44. for i, s := range b.Sigs {
  45. out[i] = s.Name
  46. }
  47. return out
  48. }
  49. var (
  50. headingRe = regexp.MustCompile(`^(#{1,6})\s+(.*?)\s*#*\s*$`)
  51. fenceRe = regexp.MustCompile("^ {0,3}(```|~~~)")
  52. spanRe = regexp.MustCompile("`([^`]+)`")
  53. sigRe = regexp.MustCompile(`^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*(\(.*\))?$`)
  54. )
  55. // splitBlocks cuts Markdown at every heading outside fenced code.
  56. func splitBlocks(md string) (string, []*Block) {
  57. var intro strings.Builder
  58. var blocks []*Block
  59. var cur *Block
  60. var body strings.Builder
  61. inFence := false
  62. flush := func() {
  63. if cur != nil {
  64. cur.Body = strings.Trim(body.String(), "\n")
  65. blocks = append(blocks, cur)
  66. } else {
  67. intro.WriteString(body.String())
  68. }
  69. body.Reset()
  70. }
  71. for _, line := range strings.Split(md, "\n") {
  72. if fenceRe.MatchString(line) {
  73. inFence = !inFence
  74. }
  75. if !inFence {
  76. if m := headingRe.FindStringSubmatch(line); m != nil {
  77. flush()
  78. cur = &Block{Level: len(m[1]), Heading: m[2]}
  79. continue
  80. }
  81. }
  82. body.WriteString(line)
  83. body.WriteByte('\n')
  84. }
  85. flush()
  86. return strings.Trim(intro.String(), "\n"), blocks
  87. }
  88. // parseHeading recognises function headings: one or more backticked
  89. // signatures, optionally separated by " / ", optionally followed by
  90. // "→ returns" and a remark such as "(admin only)".
  91. func parseHeading(b *Block, known map[string]bool) {
  92. // "Pattern 2 — `available()` polling" mentions a function but is about
  93. // something else: a function heading starts with the signature.
  94. if !strings.HasPrefix(strings.TrimSpace(b.Heading), "`") {
  95. return
  96. }
  97. left, right, hasRet := strings.Cut(b.Heading, "→")
  98. for _, m := range spanRe.FindAllStringSubmatch(left, -1) {
  99. inner := strings.TrimSpace(m[1])
  100. sm := sigRe.FindStringSubmatch(inner)
  101. if sm == nil {
  102. continue
  103. }
  104. if sm[2] == "" && !known[sm[1]] {
  105. continue // a bare word in backticks, not a call
  106. }
  107. b.Sigs = append(b.Sigs, sigSpan{Name: sm[1], Sig: inner})
  108. }
  109. if len(b.Sigs) == 0 {
  110. return
  111. }
  112. b.IsFn = true
  113. if hasRet {
  114. b.Ret = strings.TrimSpace(strings.ReplaceAll(right, "`", ""))
  115. }
  116. rest := spanRe.ReplaceAllString(left, "")
  117. rest = strings.Trim(strings.ReplaceAll(rest, "/", " "), " ")
  118. rest = strings.TrimSpace(rest)
  119. if rest != "" {
  120. b.Badges = append(b.Badges, strings.Trim(rest, "()"))
  121. }
  122. }
  123. // loadReferences reads reference/*.md and pairs each page with its api.json
  124. // section. Sections without a page still get one, drawn from api.json alone.
  125. func loadReferences(dir string, api *API, rep *report) ([]*RefPage, error) {
  126. files, err := filepath.Glob(filepath.Join(dir, "*.md"))
  127. if err != nil {
  128. return nil, err
  129. }
  130. byID := map[string]*Section{}
  131. for _, s := range api.Sections {
  132. byID[s.ID] = s
  133. }
  134. used := map[string]bool{}
  135. var pages []*RefPage
  136. for _, f := range files {
  137. raw, err := os.ReadFile(f)
  138. if err != nil {
  139. return nil, err
  140. }
  141. fm, body, err := splitFrontMatter(string(raw))
  142. if err != nil {
  143. return nil, fmt.Errorf("%s: %w", f, err)
  144. }
  145. id := strings.TrimSuffix(filepath.Base(f), ".md")
  146. p := &RefPage{ID: id, Title: fm["title"], Desc: fm["summary"], Load: fm["load"], Order: atoiDefault(fm["order"], 1000)}
  147. if sid := fm["section"]; sid != "" {
  148. s, ok := byID[sid]
  149. if !ok {
  150. return nil, fmt.Errorf("%s: section %q is not in api.json", f, sid)
  151. }
  152. if used[sid] {
  153. return nil, fmt.Errorf("%s: section %q already has a page", f, sid)
  154. }
  155. used[sid] = true
  156. p.Section = s
  157. } else {
  158. rep.pageOnly = append(rep.pageOnly, id)
  159. }
  160. p.Intro, p.Blocks = splitBlocks(body)
  161. pages = append(pages, p)
  162. }
  163. for i, s := range api.Sections {
  164. if !used[s.ID] {
  165. rep.noPage = append(rep.noPage, s.ID)
  166. pages = append(pages, &RefPage{ID: s.ID, Order: 5000 + i, Section: s})
  167. }
  168. }
  169. for _, p := range pages {
  170. p.fill()
  171. p.match(rep)
  172. }
  173. sort.SliceStable(pages, func(i, j int) bool { return pages[i].Order < pages[j].Order })
  174. return pages, nil
  175. }
  176. // fill takes the title, summary and load line from api.json where the page
  177. // does not set its own.
  178. func (p *RefPage) fill() {
  179. if s := p.Section; s != nil {
  180. if p.Title == "" {
  181. p.Title = s.Name
  182. }
  183. if p.Desc == "" {
  184. p.Desc = s.Desc
  185. }
  186. if p.Load == "" {
  187. p.Load = s.Load
  188. }
  189. }
  190. if p.Title == "" {
  191. p.Title = p.ID
  192. }
  193. }
  194. // match pairs function headings with api.json entries. An entry without a
  195. // heading of its own is placed right after the block of the entry before it
  196. // in api.json, so related functions stay together.
  197. func (p *RefPage) match(rep *report) {
  198. known := map[string]bool{}
  199. var fns []*Function
  200. if p.Section != nil {
  201. fns = p.Section.Functions
  202. }
  203. for _, f := range fns {
  204. for _, n := range f.Names() {
  205. known[n] = true
  206. }
  207. }
  208. owner := map[*Function]*Block{}
  209. for _, b := range p.Blocks {
  210. parseHeading(b, known)
  211. if !b.IsFn {
  212. continue
  213. }
  214. names := map[string]bool{}
  215. for _, n := range b.Names() {
  216. names[n] = true
  217. }
  218. for _, f := range fns {
  219. if owner[f] != nil {
  220. continue
  221. }
  222. for _, n := range f.Names() {
  223. if names[n] {
  224. owner[f] = b
  225. b.Entries = append(b.Entries, f)
  226. break
  227. }
  228. }
  229. }
  230. if len(b.Entries) == 0 {
  231. for _, n := range b.Names() {
  232. rep.missingInAPI = append(rep.missingInAPI, p.ID+": "+n)
  233. }
  234. }
  235. }
  236. var last *Block
  237. for _, f := range fns {
  238. if b := owner[f]; b != nil {
  239. last = b
  240. continue
  241. }
  242. rep.noHeading = append(rep.noHeading, f.Name)
  243. // Prefer the block whose text introduces the function, such as a
  244. // list of related calls under "History actions".
  245. if b := p.mentioning(f); b != nil {
  246. b.After = append(b.After, f)
  247. continue
  248. }
  249. if last == nil {
  250. p.Leading = append(p.Leading, f)
  251. } else {
  252. last.After = append(last.After, f)
  253. }
  254. }
  255. }
  256. // mentioning returns the first block whose Markdown names one of f's
  257. // identifiers as a call in code (`name(`), if any.
  258. func (p *RefPage) mentioning(f *Function) *Block {
  259. for _, b := range p.Blocks {
  260. for _, n := range f.Names() {
  261. if strings.Contains(b.Body, "`"+n+"(") {
  262. return b
  263. }
  264. }
  265. }
  266. return nil
  267. }
  268. // AllFunctions lists what the page documents, api.json entries first, for
  269. // the function index, the search and the playground catalogue.
  270. type FnInfo struct {
  271. Names []string `json:"names"`
  272. Sig string `json:"sig"`
  273. Ret string `json:"ret,omitempty"`
  274. Desc string `json:"desc,omitempty"`
  275. Example string `json:"example,omitempty"`
  276. Anchor string `json:"-"`
  277. }
  278. func (p *RefPage) AllFunctions() []FnInfo {
  279. var out []FnInfo
  280. add := func(f *Function) {
  281. out = append(out, FnInfo{Names: f.Names(), Sig: f.Sig, Ret: f.Ret, Desc: f.Desc, Example: f.Example, Anchor: anchorFor(f.Names())})
  282. }
  283. for _, f := range p.Leading {
  284. add(f)
  285. }
  286. for _, b := range p.Blocks {
  287. if b.IsFn {
  288. if len(b.Entries) == 0 {
  289. sigs := make([]string, len(b.Sigs))
  290. for i, s := range b.Sigs {
  291. sigs[i] = s.Sig
  292. }
  293. out = append(out, FnInfo{Names: b.Names(), Sig: strings.Join(sigs, " / "), Ret: b.Ret, Desc: firstSentence(b.Body), Anchor: anchorFor(b.Names())})
  294. }
  295. for _, f := range b.Entries {
  296. add(f)
  297. }
  298. }
  299. for _, f := range b.After {
  300. add(f)
  301. }
  302. }
  303. return out
  304. }
  305. // anchorFor is the element id of a function card: its first name.
  306. func anchorFor(names []string) string {
  307. if len(names) == 0 {
  308. return ""
  309. }
  310. return names[0]
  311. }
  312. var mdNoiseRe = regexp.MustCompile("`|\\*\\*|\\[([^\\]]*)\\]\\([^)]*\\)")
  313. // firstSentence is a plain-text summary of a Markdown body.
  314. func firstSentence(md string) string {
  315. for _, para := range strings.Split(md, "\n\n") {
  316. para = strings.TrimSpace(para)
  317. if para == "" || strings.HasPrefix(para, "```") || strings.HasPrefix(para, "|") || strings.HasPrefix(para, ">") {
  318. continue
  319. }
  320. para = strings.Join(strings.Fields(para), " ")
  321. para = mdNoiseRe.ReplaceAllString(para, "$1")
  322. if i := strings.Index(para, ". "); i > 0 {
  323. para = para[:i+1]
  324. }
  325. return para
  326. }
  327. return ""
  328. }