25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

721 lines
17 KiB

  1. // doc generates HTML files from the comments in header files.
  2. //
  3. // doc expects to be given the path to a JSON file via the --config option.
  4. // From that JSON (which is defined by the Config struct) it reads a list of
  5. // header file locations and generates HTML files for each in the current
  6. // directory.
  7. package main
  8. import (
  9. "bufio"
  10. "encoding/json"
  11. "errors"
  12. "flag"
  13. "fmt"
  14. "html/template"
  15. "io/ioutil"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. )
  20. // Config describes the structure of the config JSON file.
  21. type Config struct {
  22. // BaseDirectory is a path to which other paths in the file are
  23. // relative.
  24. BaseDirectory string
  25. Sections []ConfigSection
  26. }
  27. type ConfigSection struct {
  28. Name string
  29. // Headers is a list of paths to header files.
  30. Headers []string
  31. }
  32. // HeaderFile is the internal representation of a header file.
  33. type HeaderFile struct {
  34. // Name is the basename of the header file (e.g. "ex_data.html").
  35. Name string
  36. // Preamble contains a comment for the file as a whole. Each string
  37. // is a separate paragraph.
  38. Preamble []string
  39. Sections []HeaderSection
  40. // AllDecls maps all decls to their URL fragments.
  41. AllDecls map[string]string
  42. }
  43. type HeaderSection struct {
  44. // Preamble contains a comment for a group of functions.
  45. Preamble []string
  46. Decls []HeaderDecl
  47. // Anchor, if non-empty, is the URL fragment to use in anchor tags.
  48. Anchor string
  49. // IsPrivate is true if the section contains private functions (as
  50. // indicated by its name).
  51. IsPrivate bool
  52. }
  53. type HeaderDecl struct {
  54. // Comment contains a comment for a specific function. Each string is a
  55. // paragraph. Some paragraph may contain \n runes to indicate that they
  56. // are preformatted.
  57. Comment []string
  58. // Name contains the name of the function, if it could be extracted.
  59. Name string
  60. // Decl contains the preformatted C declaration itself.
  61. Decl string
  62. // Anchor, if non-empty, is the URL fragment to use in anchor tags.
  63. Anchor string
  64. }
  65. const (
  66. cppGuard = "#if defined(__cplusplus)"
  67. commentStart = "/* "
  68. commentEnd = " */"
  69. )
  70. func extractComment(lines []string, lineNo int) (comment []string, rest []string, restLineNo int, err error) {
  71. if len(lines) == 0 {
  72. return nil, lines, lineNo, nil
  73. }
  74. restLineNo = lineNo
  75. rest = lines
  76. if !strings.HasPrefix(rest[0], commentStart) {
  77. panic("extractComment called on non-comment")
  78. }
  79. commentParagraph := rest[0][len(commentStart):]
  80. rest = rest[1:]
  81. restLineNo++
  82. for len(rest) > 0 {
  83. i := strings.Index(commentParagraph, commentEnd)
  84. if i >= 0 {
  85. if i != len(commentParagraph)-len(commentEnd) {
  86. err = fmt.Errorf("garbage after comment end on line %d", restLineNo)
  87. return
  88. }
  89. commentParagraph = commentParagraph[:i]
  90. if len(commentParagraph) > 0 {
  91. comment = append(comment, commentParagraph)
  92. }
  93. return
  94. }
  95. line := rest[0]
  96. if !strings.HasPrefix(line, " *") {
  97. err = fmt.Errorf("comment doesn't start with block prefix on line %d: %s", restLineNo, line)
  98. return
  99. }
  100. if len(line) == 2 || line[2] != '/' {
  101. line = line[2:]
  102. }
  103. if strings.HasPrefix(line, " ") {
  104. /* Identing the lines of a paragraph marks them as
  105. * preformatted. */
  106. if len(commentParagraph) > 0 {
  107. commentParagraph += "\n"
  108. }
  109. line = line[3:]
  110. }
  111. if len(line) > 0 {
  112. commentParagraph = commentParagraph + line
  113. if len(commentParagraph) > 0 && commentParagraph[0] == ' ' {
  114. commentParagraph = commentParagraph[1:]
  115. }
  116. } else {
  117. comment = append(comment, commentParagraph)
  118. commentParagraph = ""
  119. }
  120. rest = rest[1:]
  121. restLineNo++
  122. }
  123. err = errors.New("hit EOF in comment")
  124. return
  125. }
  126. func extractDecl(lines []string, lineNo int) (decl string, rest []string, restLineNo int, err error) {
  127. if len(lines) == 0 {
  128. return "", lines, lineNo, nil
  129. }
  130. rest = lines
  131. restLineNo = lineNo
  132. var stack []rune
  133. for len(rest) > 0 {
  134. line := rest[0]
  135. for _, c := range line {
  136. switch c {
  137. case '(', '{', '[':
  138. stack = append(stack, c)
  139. case ')', '}', ']':
  140. if len(stack) == 0 {
  141. err = fmt.Errorf("unexpected %c on line %d", c, restLineNo)
  142. return
  143. }
  144. var expected rune
  145. switch c {
  146. case ')':
  147. expected = '('
  148. case '}':
  149. expected = '{'
  150. case ']':
  151. expected = '['
  152. default:
  153. panic("internal error")
  154. }
  155. if last := stack[len(stack)-1]; last != expected {
  156. err = fmt.Errorf("found %c when expecting %c on line %d", c, last, restLineNo)
  157. return
  158. }
  159. stack = stack[:len(stack)-1]
  160. }
  161. }
  162. if len(decl) > 0 {
  163. decl += "\n"
  164. }
  165. decl += line
  166. rest = rest[1:]
  167. restLineNo++
  168. if len(stack) == 0 && (len(decl) == 0 || decl[len(decl)-1] != '\\') {
  169. break
  170. }
  171. }
  172. return
  173. }
  174. func skipLine(s string) string {
  175. i := strings.Index(s, "\n")
  176. if i > 0 {
  177. return s[i:]
  178. }
  179. return ""
  180. }
  181. func getNameFromDecl(decl string) (string, bool) {
  182. for strings.HasPrefix(decl, "#if") || strings.HasPrefix(decl, "#elif") {
  183. decl = skipLine(decl)
  184. }
  185. if strings.HasPrefix(decl, "typedef ") {
  186. return "", false
  187. }
  188. for _, prefix := range []string{"struct ", "enum ", "#define "} {
  189. if !strings.HasPrefix(decl, prefix) {
  190. continue
  191. }
  192. decl = strings.TrimPrefix(decl, prefix)
  193. for len(decl) > 0 && decl[0] == ' ' {
  194. decl = decl[1:]
  195. }
  196. // struct and enum types can be the return type of a
  197. // function.
  198. if prefix[0] != '#' && strings.Index(decl, "{") == -1 {
  199. break
  200. }
  201. i := strings.IndexAny(decl, "( ")
  202. if i < 0 {
  203. return "", false
  204. }
  205. return decl[:i], true
  206. }
  207. decl = strings.TrimPrefix(decl, "OPENSSL_EXPORT ")
  208. decl = strings.TrimPrefix(decl, "STACK_OF(")
  209. decl = strings.TrimPrefix(decl, "LHASH_OF(")
  210. i := strings.Index(decl, "(")
  211. if i < 0 {
  212. return "", false
  213. }
  214. j := strings.LastIndex(decl[:i], " ")
  215. if j < 0 {
  216. return "", false
  217. }
  218. for j+1 < len(decl) && decl[j+1] == '*' {
  219. j++
  220. }
  221. return decl[j+1 : i], true
  222. }
  223. func sanitizeAnchor(name string) string {
  224. return strings.Replace(name, " ", "-", -1)
  225. }
  226. func isPrivateSection(name string) bool {
  227. return strings.HasPrefix(name, "Private functions") || strings.HasPrefix(name, "Private structures") || strings.Contains(name, "(hidden)")
  228. }
  229. func (config *Config) parseHeader(path string) (*HeaderFile, error) {
  230. headerPath := filepath.Join(config.BaseDirectory, path)
  231. headerFile, err := os.Open(headerPath)
  232. if err != nil {
  233. return nil, err
  234. }
  235. defer headerFile.Close()
  236. scanner := bufio.NewScanner(headerFile)
  237. var lines, oldLines []string
  238. for scanner.Scan() {
  239. lines = append(lines, scanner.Text())
  240. }
  241. if err := scanner.Err(); err != nil {
  242. return nil, err
  243. }
  244. lineNo := 0
  245. found := false
  246. for i, line := range lines {
  247. lineNo++
  248. if line == cppGuard {
  249. lines = lines[i+1:]
  250. lineNo++
  251. found = true
  252. break
  253. }
  254. }
  255. if !found {
  256. return nil, errors.New("no C++ guard found")
  257. }
  258. if len(lines) == 0 || lines[0] != "extern \"C\" {" {
  259. return nil, errors.New("no extern \"C\" found after C++ guard")
  260. }
  261. lineNo += 2
  262. lines = lines[2:]
  263. header := &HeaderFile{
  264. Name: filepath.Base(path),
  265. AllDecls: make(map[string]string),
  266. }
  267. for i, line := range lines {
  268. lineNo++
  269. if len(line) > 0 {
  270. lines = lines[i:]
  271. break
  272. }
  273. }
  274. oldLines = lines
  275. if len(lines) > 0 && strings.HasPrefix(lines[0], commentStart) {
  276. comment, rest, restLineNo, err := extractComment(lines, lineNo)
  277. if err != nil {
  278. return nil, err
  279. }
  280. if len(rest) > 0 && len(rest[0]) == 0 {
  281. if len(rest) < 2 || len(rest[1]) != 0 {
  282. return nil, errors.New("preamble comment should be followed by two blank lines")
  283. }
  284. header.Preamble = comment
  285. lineNo = restLineNo + 2
  286. lines = rest[2:]
  287. } else {
  288. lines = oldLines
  289. }
  290. }
  291. allAnchors := make(map[string]struct{})
  292. for {
  293. // Start of a section.
  294. if len(lines) == 0 {
  295. return nil, errors.New("unexpected end of file")
  296. }
  297. line := lines[0]
  298. if line == cppGuard {
  299. break
  300. }
  301. if len(line) == 0 {
  302. return nil, fmt.Errorf("blank line at start of section on line %d", lineNo)
  303. }
  304. var section HeaderSection
  305. if strings.HasPrefix(line, commentStart) {
  306. comment, rest, restLineNo, err := extractComment(lines, lineNo)
  307. if err != nil {
  308. return nil, err
  309. }
  310. if len(rest) > 0 && len(rest[0]) == 0 {
  311. anchor := sanitizeAnchor(firstSentence(comment))
  312. if len(anchor) > 0 {
  313. if _, ok := allAnchors[anchor]; ok {
  314. return nil, fmt.Errorf("duplicate anchor: %s", anchor)
  315. }
  316. allAnchors[anchor] = struct{}{}
  317. }
  318. section.Preamble = comment
  319. section.IsPrivate = len(comment) > 0 && isPrivateSection(comment[0])
  320. section.Anchor = anchor
  321. lines = rest[1:]
  322. lineNo = restLineNo + 1
  323. }
  324. }
  325. for len(lines) > 0 {
  326. line := lines[0]
  327. if len(line) == 0 {
  328. lines = lines[1:]
  329. lineNo++
  330. break
  331. }
  332. if line == cppGuard {
  333. return nil, errors.New("hit ending C++ guard while in section")
  334. }
  335. var comment []string
  336. var decl string
  337. if strings.HasPrefix(line, commentStart) {
  338. comment, lines, lineNo, err = extractComment(lines, lineNo)
  339. if err != nil {
  340. return nil, err
  341. }
  342. }
  343. if len(lines) == 0 {
  344. return nil, errors.New("expected decl at EOF")
  345. }
  346. decl, lines, lineNo, err = extractDecl(lines, lineNo)
  347. if err != nil {
  348. return nil, err
  349. }
  350. name, ok := getNameFromDecl(decl)
  351. if !ok {
  352. name = ""
  353. }
  354. if last := len(section.Decls) - 1; len(name) == 0 && len(comment) == 0 && last >= 0 {
  355. section.Decls[last].Decl += "\n" + decl
  356. } else {
  357. // As a matter of style, comments should start
  358. // with the name of the thing that they are
  359. // commenting on. We make an exception here for
  360. // #defines (because we often have blocks of
  361. // them) and collective comments, which are
  362. // detected by starting with “The” or “These”.
  363. if len(comment) > 0 &&
  364. !strings.HasPrefix(comment[0], name) &&
  365. !strings.HasPrefix(decl, "#define ") &&
  366. !strings.HasPrefix(comment[0], "The ") &&
  367. !strings.HasPrefix(comment[0], "These ") {
  368. return nil, fmt.Errorf("Comment for %q doesn't seem to match just above %s:%d\n", name, path, lineNo)
  369. }
  370. anchor := sanitizeAnchor(name)
  371. // TODO(davidben): Enforce uniqueness. This is
  372. // skipped because #ifdefs currently result in
  373. // duplicate table-of-contents entries.
  374. allAnchors[anchor] = struct{}{}
  375. header.AllDecls[name] = anchor
  376. section.Decls = append(section.Decls, HeaderDecl{
  377. Comment: comment,
  378. Name: name,
  379. Decl: decl,
  380. Anchor: anchor,
  381. })
  382. }
  383. if len(lines) > 0 && len(lines[0]) == 0 {
  384. lines = lines[1:]
  385. lineNo++
  386. }
  387. }
  388. header.Sections = append(header.Sections, section)
  389. }
  390. return header, nil
  391. }
  392. func firstSentence(paragraphs []string) string {
  393. if len(paragraphs) == 0 {
  394. return ""
  395. }
  396. s := paragraphs[0]
  397. i := strings.Index(s, ". ")
  398. if i >= 0 {
  399. return s[:i]
  400. }
  401. if lastIndex := len(s) - 1; s[lastIndex] == '.' {
  402. return s[:lastIndex]
  403. }
  404. return s
  405. }
  406. func markupPipeWords(allDecls map[string]string, s string) template.HTML {
  407. ret := ""
  408. for {
  409. i := strings.Index(s, "|")
  410. if i == -1 {
  411. ret += s
  412. break
  413. }
  414. ret += s[:i]
  415. s = s[i+1:]
  416. i = strings.Index(s, "|")
  417. j := strings.Index(s, " ")
  418. if i > 0 && (j == -1 || j > i) {
  419. ret += "<tt>"
  420. anchor, isLink := allDecls[s[:i]]
  421. if isLink {
  422. ret += fmt.Sprintf("<a href=\"%s\">", template.HTMLEscapeString(anchor))
  423. }
  424. ret += s[:i]
  425. if isLink {
  426. ret += "</a>"
  427. }
  428. ret += "</tt>"
  429. s = s[i+1:]
  430. } else {
  431. ret += "|"
  432. }
  433. }
  434. return template.HTML(ret)
  435. }
  436. func markupFirstWord(s template.HTML) template.HTML {
  437. start := 0
  438. again:
  439. end := strings.Index(string(s[start:]), " ")
  440. if end > 0 {
  441. end += start
  442. w := strings.ToLower(string(s[start:end]))
  443. // The first word was already marked up as an HTML tag. Don't
  444. // mark it up further.
  445. if strings.ContainsRune(w, '<') {
  446. return s
  447. }
  448. if w == "a" || w == "an" {
  449. start = end + 1
  450. goto again
  451. }
  452. return s[:start] + "<span class=\"first-word\">" + s[start:end] + "</span>" + s[end:]
  453. }
  454. return s
  455. }
  456. func newlinesToBR(html template.HTML) template.HTML {
  457. s := string(html)
  458. if !strings.Contains(s, "\n") {
  459. return html
  460. }
  461. s = strings.Replace(s, "\n", "<br>", -1)
  462. s = strings.Replace(s, " ", "&nbsp;", -1)
  463. return template.HTML(s)
  464. }
  465. func generate(outPath string, config *Config) (map[string]string, error) {
  466. allDecls := make(map[string]string)
  467. headerTmpl := template.New("headerTmpl")
  468. headerTmpl.Funcs(template.FuncMap{
  469. "firstSentence": firstSentence,
  470. "markupPipeWords": func(s string) template.HTML { return markupPipeWords(allDecls, s) },
  471. "markupFirstWord": markupFirstWord,
  472. "newlinesToBR": newlinesToBR,
  473. })
  474. headerTmpl, err := headerTmpl.Parse(`<!DOCTYPE html>
  475. <html>
  476. <head>
  477. <title>BoringSSL - {{.Name}}</title>
  478. <meta charset="utf-8">
  479. <link rel="stylesheet" type="text/css" href="doc.css">
  480. </head>
  481. <body>
  482. <div id="main">
  483. <h2>{{.Name}}</h2>
  484. {{range .Preamble}}<p>{{. | html | markupPipeWords}}</p>{{end}}
  485. <ol>
  486. {{range .Sections}}
  487. {{if not .IsPrivate}}
  488. {{if .Anchor}}<li class="header"><a href="#{{.Anchor}}">{{.Preamble | firstSentence | html | markupPipeWords}}</a></li>{{end}}
  489. {{range .Decls}}
  490. {{if .Anchor}}<li><a href="#{{.Anchor}}"><tt>{{.Name}}</tt></a></li>{{end}}
  491. {{end}}
  492. {{end}}
  493. {{end}}
  494. </ol>
  495. {{range .Sections}}
  496. {{if not .IsPrivate}}
  497. <div class="section" {{if .Anchor}}id="{{.Anchor}}"{{end}}>
  498. {{if .Preamble}}
  499. <div class="sectionpreamble">
  500. {{range .Preamble}}<p>{{. | html | markupPipeWords}}</p>{{end}}
  501. </div>
  502. {{end}}
  503. {{range .Decls}}
  504. <div class="decl" {{if .Anchor}}id="{{.Anchor}}"{{end}}>
  505. {{range .Comment}}
  506. <p>{{. | html | markupPipeWords | newlinesToBR | markupFirstWord}}</p>
  507. {{end}}
  508. <pre>{{.Decl}}</pre>
  509. </div>
  510. {{end}}
  511. </div>
  512. {{end}}
  513. {{end}}
  514. </div>
  515. </body>
  516. </html>`)
  517. if err != nil {
  518. return nil, err
  519. }
  520. headerDescriptions := make(map[string]string)
  521. var headers []*HeaderFile
  522. for _, section := range config.Sections {
  523. for _, headerPath := range section.Headers {
  524. header, err := config.parseHeader(headerPath)
  525. if err != nil {
  526. return nil, errors.New("while parsing " + headerPath + ": " + err.Error())
  527. }
  528. headerDescriptions[header.Name] = firstSentence(header.Preamble)
  529. headers = append(headers, header)
  530. for name, anchor := range header.AllDecls {
  531. allDecls[name] = fmt.Sprintf("%s#%s", header.Name+".html", anchor)
  532. }
  533. }
  534. }
  535. for _, header := range headers {
  536. filename := filepath.Join(outPath, header.Name+".html")
  537. file, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  538. if err != nil {
  539. panic(err)
  540. }
  541. defer file.Close()
  542. if err := headerTmpl.Execute(file, header); err != nil {
  543. return nil, err
  544. }
  545. }
  546. return headerDescriptions, nil
  547. }
  548. func generateIndex(outPath string, config *Config, headerDescriptions map[string]string) error {
  549. indexTmpl := template.New("indexTmpl")
  550. indexTmpl.Funcs(template.FuncMap{
  551. "baseName": filepath.Base,
  552. "headerDescription": func(header string) string {
  553. return headerDescriptions[header]
  554. },
  555. })
  556. indexTmpl, err := indexTmpl.Parse(`<!DOCTYPE html5>
  557. <head>
  558. <title>BoringSSL - Headers</title>
  559. <meta charset="utf-8">
  560. <link rel="stylesheet" type="text/css" href="doc.css">
  561. </head>
  562. <body>
  563. <div id="main">
  564. <table>
  565. {{range .Sections}}
  566. <tr class="header"><td colspan="2">{{.Name}}</td></tr>
  567. {{range .Headers}}
  568. <tr><td><a href="{{. | baseName}}.html">{{. | baseName}}</a></td><td>{{. | baseName | headerDescription}}</td></tr>
  569. {{end}}
  570. {{end}}
  571. </table>
  572. </div>
  573. </body>
  574. </html>`)
  575. if err != nil {
  576. return err
  577. }
  578. file, err := os.OpenFile(filepath.Join(outPath, "headers.html"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  579. if err != nil {
  580. panic(err)
  581. }
  582. defer file.Close()
  583. if err := indexTmpl.Execute(file, config); err != nil {
  584. return err
  585. }
  586. return nil
  587. }
  588. func copyFile(outPath string, inFilePath string) error {
  589. bytes, err := ioutil.ReadFile(inFilePath)
  590. if err != nil {
  591. return err
  592. }
  593. return ioutil.WriteFile(filepath.Join(outPath, filepath.Base(inFilePath)), bytes, 0666)
  594. }
  595. func main() {
  596. var (
  597. configFlag *string = flag.String("config", "doc.config", "Location of config file")
  598. outputDir *string = flag.String("out", ".", "Path to the directory where the output will be written")
  599. config Config
  600. )
  601. flag.Parse()
  602. if len(*configFlag) == 0 {
  603. fmt.Printf("No config file given by --config\n")
  604. os.Exit(1)
  605. }
  606. if len(*outputDir) == 0 {
  607. fmt.Printf("No output directory given by --out\n")
  608. os.Exit(1)
  609. }
  610. configBytes, err := ioutil.ReadFile(*configFlag)
  611. if err != nil {
  612. fmt.Printf("Failed to open config file: %s\n", err)
  613. os.Exit(1)
  614. }
  615. if err := json.Unmarshal(configBytes, &config); err != nil {
  616. fmt.Printf("Failed to parse config file: %s\n", err)
  617. os.Exit(1)
  618. }
  619. headerDescriptions, err := generate(*outputDir, &config)
  620. if err != nil {
  621. fmt.Printf("Failed to generate output: %s\n", err)
  622. os.Exit(1)
  623. }
  624. if err := generateIndex(*outputDir, &config, headerDescriptions); err != nil {
  625. fmt.Printf("Failed to generate index: %s\n", err)
  626. os.Exit(1)
  627. }
  628. if err := copyFile(*outputDir, "doc.css"); err != nil {
  629. fmt.Printf("Failed to copy static file: %s\n", err)
  630. os.Exit(1)
  631. }
  632. }