blob: 20feae54d916a792cfc176b172ffede04ac931e2 [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
51 // Num is just the index of the section. It's included in order to help
52 // text/template generate anchors.
53 Num int
54 // IsPrivate is true if the section contains private functions (as
55 // indicated by its name).
56 IsPrivate bool
57}
58
59type HeaderDecl struct {
60 // Comment contains a comment for a specific function. Each string is a
61 // paragraph. Some paragraph may contain \n runes to indicate that they
62 // are preformatted.
63 Comment []string
64 // Name contains the name of the function, if it could be extracted.
65 Name string
66 // Decl contains the preformatted C declaration itself.
67 Decl string
68 // Num is an index for the declaration, but the value is unique for all
69 // declarations in a HeaderFile. It's included in order to help
70 // text/template generate anchors.
71 Num int
72}
73
74const (
75 cppGuard = "#if defined(__cplusplus)"
76 commentStart = "/* "
77 commentEnd = " */"
78)
79
80func extractComment(lines []string, lineNo int) (comment []string, rest []string, restLineNo int, err error) {
81 if len(lines) == 0 {
82 return nil, lines, lineNo, nil
83 }
84
85 restLineNo = lineNo
86 rest = lines
87
88 if !strings.HasPrefix(rest[0], commentStart) {
89 panic("extractComment called on non-comment")
90 }
91 commentParagraph := rest[0][len(commentStart):]
92 rest = rest[1:]
93 restLineNo++
94
95 for len(rest) > 0 {
96 i := strings.Index(commentParagraph, commentEnd)
97 if i >= 0 {
98 if i != len(commentParagraph)-len(commentEnd) {
99 err = fmt.Errorf("garbage after comment end on line %d", restLineNo)
100 return
101 }
102 commentParagraph = commentParagraph[:i]
103 if len(commentParagraph) > 0 {
104 comment = append(comment, commentParagraph)
105 }
106 return
107 }
108
109 line := rest[0]
110 if !strings.HasPrefix(line, " *") {
111 err = fmt.Errorf("comment doesn't start with block prefix on line %d: %s", restLineNo, line)
112 return
113 }
David Benjamin48b31502015-04-08 23:17:55 -0400114 if len(line) == 2 || line[2] != '/' {
115 line = line[2:]
116 }
Adam Langley95c29f32014-06-20 12:00:00 -0700117 if strings.HasPrefix(line, " ") {
118 /* Identing the lines of a paragraph marks them as
119 * preformatted. */
120 if len(commentParagraph) > 0 {
121 commentParagraph += "\n"
122 }
123 line = line[3:]
124 }
125 if len(line) > 0 {
126 commentParagraph = commentParagraph + line
127 if len(commentParagraph) > 0 && commentParagraph[0] == ' ' {
128 commentParagraph = commentParagraph[1:]
129 }
130 } else {
131 comment = append(comment, commentParagraph)
132 commentParagraph = ""
133 }
134 rest = rest[1:]
135 restLineNo++
136 }
137
138 err = errors.New("hit EOF in comment")
139 return
140}
141
142func extractDecl(lines []string, lineNo int) (decl string, rest []string, restLineNo int, err error) {
143 if len(lines) == 0 {
144 return "", lines, lineNo, nil
145 }
146
147 rest = lines
148 restLineNo = lineNo
149
150 var stack []rune
151 for len(rest) > 0 {
152 line := rest[0]
153 for _, c := range line {
154 switch c {
155 case '(', '{', '[':
156 stack = append(stack, c)
157 case ')', '}', ']':
158 if len(stack) == 0 {
159 err = fmt.Errorf("unexpected %c on line %d", c, restLineNo)
160 return
161 }
162 var expected rune
163 switch c {
164 case ')':
165 expected = '('
166 case '}':
167 expected = '{'
168 case ']':
169 expected = '['
170 default:
171 panic("internal error")
172 }
173 if last := stack[len(stack)-1]; last != expected {
174 err = fmt.Errorf("found %c when expecting %c on line %d", c, last, restLineNo)
175 return
176 }
177 stack = stack[:len(stack)-1]
178 }
179 }
180 if len(decl) > 0 {
181 decl += "\n"
182 }
183 decl += line
184 rest = rest[1:]
185 restLineNo++
186
187 if len(stack) == 0 && (len(decl) == 0 || decl[len(decl)-1] != '\\') {
188 break
189 }
190 }
191
192 return
193}
194
195func skipPast(s, skip string) string {
196 i := strings.Index(s, skip)
197 if i > 0 {
David Benjamin48b31502015-04-08 23:17:55 -0400198 return s[i:]
Adam Langley95c29f32014-06-20 12:00:00 -0700199 }
200 return s
201}
202
David Benjamin71485af2015-04-09 00:06:03 -0400203func skipLine(s string) string {
204 i := strings.Index(s, "\n")
205 if i > 0 {
206 return s[i:]
207 }
208 return ""
209}
210
Adam Langley95c29f32014-06-20 12:00:00 -0700211func getNameFromDecl(decl string) (string, bool) {
David Benjamin71485af2015-04-09 00:06:03 -0400212 for strings.HasPrefix(decl, "#if") {
213 decl = skipLine(decl)
214 }
Adam Langley95c29f32014-06-20 12:00:00 -0700215 if strings.HasPrefix(decl, "struct ") {
216 return "", false
217 }
218 decl = skipPast(decl, "STACK_OF(")
219 decl = skipPast(decl, "LHASH_OF(")
220 i := strings.Index(decl, "(")
221 if i < 0 {
222 return "", false
223 }
224 j := strings.LastIndex(decl[:i], " ")
225 if j < 0 {
226 return "", false
227 }
228 for j+1 < len(decl) && decl[j+1] == '*' {
229 j++
230 }
231 return decl[j+1 : i], true
232}
233
234func (config *Config) parseHeader(path string) (*HeaderFile, error) {
235 headerPath := filepath.Join(config.BaseDirectory, path)
236
237 headerFile, err := os.Open(headerPath)
238 if err != nil {
239 return nil, err
240 }
241 defer headerFile.Close()
242
243 scanner := bufio.NewScanner(headerFile)
244 var lines, oldLines []string
245 for scanner.Scan() {
246 lines = append(lines, scanner.Text())
247 }
248 if err := scanner.Err(); err != nil {
249 return nil, err
250 }
251
252 lineNo := 0
253 found := false
254 for i, line := range lines {
255 lineNo++
256 if line == cppGuard {
257 lines = lines[i+1:]
258 lineNo++
259 found = true
260 break
261 }
262 }
263
264 if !found {
265 return nil, errors.New("no C++ guard found")
266 }
267
268 if len(lines) == 0 || lines[0] != "extern \"C\" {" {
269 return nil, errors.New("no extern \"C\" found after C++ guard")
270 }
271 lineNo += 2
272 lines = lines[2:]
273
274 header := &HeaderFile{
275 Name: filepath.Base(path),
276 }
277
278 for i, line := range lines {
279 lineNo++
280 if len(line) > 0 {
281 lines = lines[i:]
282 break
283 }
284 }
285
286 oldLines = lines
287 if len(lines) > 0 && strings.HasPrefix(lines[0], commentStart) {
288 comment, rest, restLineNo, err := extractComment(lines, lineNo)
289 if err != nil {
290 return nil, err
291 }
292
293 if len(rest) > 0 && len(rest[0]) == 0 {
294 if len(rest) < 2 || len(rest[1]) != 0 {
295 return nil, errors.New("preamble comment should be followed by two blank lines")
296 }
297 header.Preamble = comment
298 lineNo = restLineNo + 2
299 lines = rest[2:]
300 } else {
301 lines = oldLines
302 }
303 }
304
305 var sectionNumber, declNumber int
306
307 for {
308 // Start of a section.
309 if len(lines) == 0 {
310 return nil, errors.New("unexpected end of file")
311 }
312 line := lines[0]
313 if line == cppGuard {
314 break
315 }
316
317 if len(line) == 0 {
318 return nil, fmt.Errorf("blank line at start of section on line %d", lineNo)
319 }
320
321 section := HeaderSection{
322 Num: sectionNumber,
323 }
324 sectionNumber++
325
326 if strings.HasPrefix(line, commentStart) {
327 comment, rest, restLineNo, err := extractComment(lines, lineNo)
328 if err != nil {
329 return nil, err
330 }
331 if len(rest) > 0 && len(rest[0]) == 0 {
332 section.Preamble = comment
333 section.IsPrivate = len(comment) > 0 && strings.HasPrefix(comment[0], "Private functions")
334 lines = rest[1:]
335 lineNo = restLineNo + 1
336 }
337 }
338
339 for len(lines) > 0 {
340 line := lines[0]
341 if len(line) == 0 {
342 lines = lines[1:]
343 lineNo++
344 break
345 }
346 if line == cppGuard {
347 return nil, errors.New("hit ending C++ guard while in section")
348 }
349
350 var comment []string
351 var decl string
352 if strings.HasPrefix(line, commentStart) {
353 comment, lines, lineNo, err = extractComment(lines, lineNo)
354 if err != nil {
355 return nil, err
356 }
357 }
358 if len(lines) == 0 {
359 return nil, errors.New("expected decl at EOF")
360 }
361 decl, lines, lineNo, err = extractDecl(lines, lineNo)
362 if err != nil {
363 return nil, err
364 }
365 name, ok := getNameFromDecl(decl)
366 if !ok {
367 name = ""
368 }
369 if last := len(section.Decls) - 1; len(name) == 0 && len(comment) == 0 && last >= 0 {
370 section.Decls[last].Decl += "\n" + decl
371 } else {
372 section.Decls = append(section.Decls, HeaderDecl{
373 Comment: comment,
374 Name: name,
375 Decl: decl,
376 Num: declNumber,
377 })
378 declNumber++
379 }
380
381 if len(lines) > 0 && len(lines[0]) == 0 {
382 lines = lines[1:]
383 lineNo++
384 }
385 }
386
387 header.Sections = append(header.Sections, section)
388 }
389
390 return header, nil
391}
392
393func firstSentence(paragraphs []string) string {
394 if len(paragraphs) == 0 {
395 return ""
396 }
397 s := paragraphs[0]
398 i := strings.Index(s, ". ")
399 if i >= 0 {
400 return s[:i]
401 }
402 if lastIndex := len(s) - 1; s[lastIndex] == '.' {
403 return s[:lastIndex]
404 }
405 return s
406}
407
408func markupPipeWords(s string) template.HTML {
409 ret := ""
410
411 for {
412 i := strings.Index(s, "|")
413 if i == -1 {
414 ret += s
415 break
416 }
417 ret += s[:i]
418 s = s[i+1:]
419
420 i = strings.Index(s, "|")
421 j := strings.Index(s, " ")
422 if i > 0 && (j == -1 || j > i) {
423 ret += "<tt>"
424 ret += s[:i]
425 ret += "</tt>"
426 s = s[i+1:]
427 } else {
428 ret += "|"
429 }
430 }
431
432 return template.HTML(ret)
433}
434
435func markupFirstWord(s template.HTML) template.HTML {
David Benjamin5b082e82014-12-26 00:54:52 -0500436 start := 0
437again:
438 end := strings.Index(string(s[start:]), " ")
439 if end > 0 {
440 end += start
441 w := strings.ToLower(string(s[start:end]))
442 if w == "a" || w == "an" || w == "deprecated:" {
443 start = end + 1
444 goto again
445 }
446 return s[:start] + "<span class=\"first-word\">" + s[start:end] + "</span>" + s[end:]
Adam Langley95c29f32014-06-20 12:00:00 -0700447 }
448 return s
449}
450
451func newlinesToBR(html template.HTML) template.HTML {
452 s := string(html)
453 if !strings.Contains(s, "\n") {
454 return html
455 }
456 s = strings.Replace(s, "\n", "<br>", -1)
457 s = strings.Replace(s, " ", "&nbsp;", -1)
458 return template.HTML(s)
459}
460
461func generate(outPath string, config *Config) (map[string]string, error) {
462 headerTmpl := template.New("headerTmpl")
463 headerTmpl.Funcs(template.FuncMap{
464 "firstSentence": firstSentence,
465 "markupPipeWords": markupPipeWords,
466 "markupFirstWord": markupFirstWord,
467 "newlinesToBR": newlinesToBR,
468 })
David Benjamin5b082e82014-12-26 00:54:52 -0500469 headerTmpl, err := headerTmpl.Parse(`<!DOCTYPE html>
Adam Langley95c29f32014-06-20 12:00:00 -0700470<html>
471 <head>
472 <title>BoringSSL - {{.Name}}</title>
473 <meta charset="utf-8">
474 <link rel="stylesheet" type="text/css" href="doc.css">
475 </head>
476
477 <body>
478 <div id="main">
479 <h2>{{.Name}}</h2>
480
481 {{range .Preamble}}<p>{{. | html | markupPipeWords}}</p>{{end}}
482
483 <ol>
484 {{range .Sections}}
485 {{if not .IsPrivate}}
David Benjamin5b082e82014-12-26 00:54:52 -0500486 {{if .Preamble}}<li class="header"><a href="#section-{{.Num}}">{{.Preamble | firstSentence | html | markupPipeWords}}</a></li>{{end}}
Adam Langley95c29f32014-06-20 12:00:00 -0700487 {{range .Decls}}
488 {{if .Name}}<li><a href="#decl-{{.Num}}"><tt>{{.Name}}</tt></a></li>{{end}}
489 {{end}}
490 {{end}}
491 {{end}}
492 </ol>
493
494 {{range .Sections}}
495 {{if not .IsPrivate}}
496 <div class="section">
497 {{if .Preamble}}
498 <div class="sectionpreamble">
499 <a name="section-{{.Num}}">
500 {{range .Preamble}}<p>{{. | html | markupPipeWords}}</p>{{end}}
501 </a>
502 </div>
503 {{end}}
504
505 {{range .Decls}}
506 <div class="decl">
507 <a name="decl-{{.Num}}">
508 {{range .Comment}}
509 <p>{{. | html | markupPipeWords | newlinesToBR | markupFirstWord}}</p>
510 {{end}}
511 <pre>{{.Decl}}</pre>
512 </a>
513 </div>
514 {{end}}
515 </div>
516 {{end}}
517 {{end}}
518 </div>
519 </body>
520</html>`)
521 if err != nil {
522 return nil, err
523 }
524
525 headerDescriptions := make(map[string]string)
526
527 for _, section := range config.Sections {
528 for _, headerPath := range section.Headers {
529 header, err := config.parseHeader(headerPath)
530 if err != nil {
531 return nil, errors.New("while parsing " + headerPath + ": " + err.Error())
532 }
533 headerDescriptions[header.Name] = firstSentence(header.Preamble)
534 filename := filepath.Join(outPath, header.Name+".html")
535 file, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
536 if err != nil {
537 panic(err)
538 }
539 defer file.Close()
540 if err := headerTmpl.Execute(file, header); err != nil {
541 return nil, err
542 }
543 }
544 }
545
546 return headerDescriptions, nil
547}
548
549func generateIndex(outPath string, config *Config, headerDescriptions map[string]string) error {
550 indexTmpl := template.New("indexTmpl")
551 indexTmpl.Funcs(template.FuncMap{
552 "baseName": filepath.Base,
553 "headerDescription": func(header string) string {
554 return headerDescriptions[header]
555 },
556 })
557 indexTmpl, err := indexTmpl.Parse(`<!DOCTYPE html5>
558
559 <head>
560 <title>BoringSSL - Headers</title>
561 <meta charset="utf-8">
562 <link rel="stylesheet" type="text/css" href="doc.css">
563 </head>
564
565 <body>
566 <div id="main">
567 <table>
568 {{range .Sections}}
569 <tr class="header"><td colspan="2">{{.Name}}</td></tr>
570 {{range .Headers}}
571 <tr><td><a href="{{. | baseName}}.html">{{. | baseName}}</a></td><td>{{. | baseName | headerDescription}}</td></tr>
572 {{end}}
573 {{end}}
574 </table>
575 </div>
576 </body>
577</html>`)
578
579 if err != nil {
580 return err
581 }
582
583 file, err := os.OpenFile(filepath.Join(outPath, "headers.html"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
584 if err != nil {
585 panic(err)
586 }
587 defer file.Close()
588
589 if err := indexTmpl.Execute(file, config); err != nil {
590 return err
591 }
592
593 return nil
594}
595
596func main() {
597 var (
Adam Langley0fd56392015-04-08 17:32:55 -0700598 configFlag *string = flag.String("config", "doc.config", "Location of config file")
599 outputDir *string = flag.String("out", ".", "Path to the directory where the output will be written")
Adam Langley95c29f32014-06-20 12:00:00 -0700600 config Config
601 )
602
603 flag.Parse()
604
605 if len(*configFlag) == 0 {
606 fmt.Printf("No config file given by --config\n")
607 os.Exit(1)
608 }
609
610 if len(*outputDir) == 0 {
611 fmt.Printf("No output directory given by --out\n")
612 os.Exit(1)
613 }
614
615 configBytes, err := ioutil.ReadFile(*configFlag)
616 if err != nil {
617 fmt.Printf("Failed to open config file: %s\n", err)
618 os.Exit(1)
619 }
620
621 if err := json.Unmarshal(configBytes, &config); err != nil {
622 fmt.Printf("Failed to parse config file: %s\n", err)
623 os.Exit(1)
624 }
625
626 headerDescriptions, err := generate(*outputDir, &config)
627 if err != nil {
628 fmt.Printf("Failed to generate output: %s\n", err)
629 os.Exit(1)
630 }
631
632 if err := generateIndex(*outputDir, &config, headerDescriptions); err != nil {
633 fmt.Printf("Failed to generate index: %s\n", err)
634 os.Exit(1)
635 }
636}