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