2b2531fcf00a2823faa124a1269100f91e17e9e6
[dragonfly.git] / usr.bin / mandoc / man.c
1 /*      $Id: man.c,v 1.59 2010/03/29 10:10:35 kristaps Exp $ */
2 /*
3  * Copyright (c) 2008, 2009 Kristaps Dzonsons <kristaps@kth.se>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include <sys/types.h>
18
19 #include <assert.h>
20 #include <ctype.h>
21 #include <stdarg.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25
26 #include "libman.h"
27 #include "libmandoc.h"
28
29 const   char *const __man_merrnames[WERRMAX] = {
30         "invalid character", /* WNPRINT */
31         "invalid manual section", /* WMSEC */
32         "invalid date format", /* WDATE */
33         "scope of prior line violated", /* WLNSCOPE */
34         "over-zealous prior line scope violation", /* WLNSCOPE2 */
35         "trailing whitespace", /* WTSPACE */
36         "unterminated quoted parameter", /* WTQUOTE */
37         "document has no body", /* WNODATA */
38         "document has no title/section", /* WNOTITLE */
39         "invalid escape sequence", /* WESCAPE */
40         "invalid number format", /* WNUMFMT */
41         "expected block head arguments", /* WHEADARGS */
42         "expected block body arguments", /* WBODYARGS */
43         "expected empty block head", /* WNHEADARGS */
44         "ill-formed macro", /* WMACROFORM */
45         "scope open on exit", /* WEXITSCOPE */
46         "no scope context", /* WNOSCOPE */
47         "literal context already open", /* WOLITERAL */
48         "no literal context open", /* WNLITERAL */
49         "invalid nesting of roff declarations", /* WROFFNEST */
50         "scope in roff instructions broken", /* WROFFSCOPE */
51         "document title should be uppercase", /* WTITLECASE */
52 };
53
54 const   char *const __man_macronames[MAN_MAX] = {
55         "br",           "TH",           "SH",           "SS",
56         "TP",           "LP",           "PP",           "P",
57         "IP",           "HP",           "SM",           "SB",
58         "BI",           "IB",           "BR",           "RB",
59         "R",            "B",            "I",            "IR",
60         "RI",           "na",           "i",            "sp",
61         "nf",           "fi",           "r",            "RE",
62         "RS",           "DT",           "UC",           "PD",
63         "Sp",           "Vb",           "Ve",           "de",
64         "dei",          "am",           "ami",          "ig",
65         ".",
66         };
67
68 const   char * const *man_macronames = __man_macronames;
69
70 static  struct man_node *man_node_alloc(int, int,
71                                 enum man_type, enum mant);
72 static  int              man_node_append(struct man *,
73                                 struct man_node *);
74 static  void             man_node_free(struct man_node *);
75 static  void             man_node_unlink(struct man *,
76                                 struct man_node *);
77 static  int              man_ptext(struct man *, int, char *);
78 static  int              man_pmacro(struct man *, int, char *);
79 static  void             man_free1(struct man *);
80 static  void             man_alloc1(struct man *);
81 static  int              pstring(struct man *, int, int,
82                                 const char *, size_t);
83 static  int              macrowarn(struct man *, int, const char *);
84
85
86 const struct man_node *
87 man_node(const struct man *m)
88 {
89
90         return(MAN_HALT & m->flags ? NULL : m->first);
91 }
92
93
94 const struct man_meta *
95 man_meta(const struct man *m)
96 {
97
98         return(MAN_HALT & m->flags ? NULL : &m->meta);
99 }
100
101
102 void
103 man_reset(struct man *man)
104 {
105
106         man_free1(man);
107         man_alloc1(man);
108 }
109
110
111 void
112 man_free(struct man *man)
113 {
114
115         man_free1(man);
116         free(man);
117 }
118
119
120 struct man *
121 man_alloc(void *data, int pflags, const struct man_cb *cb)
122 {
123         struct man      *p;
124
125         p = mandoc_calloc(1, sizeof(struct man));
126
127         if (cb)
128                 memcpy(&p->cb, cb, sizeof(struct man_cb));
129
130         man_hash_init();
131         p->data = data;
132         p->pflags = pflags;
133
134         man_alloc1(p);
135         return(p);
136 }
137
138
139 int
140 man_endparse(struct man *m)
141 {
142
143         if (MAN_HALT & m->flags)
144                 return(0);
145         else if (man_macroend(m))
146                 return(1);
147         m->flags |= MAN_HALT;
148         return(0);
149 }
150
151
152 int
153 man_parseln(struct man *m, int ln, char *buf)
154 {
155
156         return('.' == *buf || '\'' == *buf ?
157                         man_pmacro(m, ln, buf) :
158                         man_ptext(m, ln, buf));
159 }
160
161
162 static void
163 man_free1(struct man *man)
164 {
165
166         if (man->first)
167                 man_node_delete(man, man->first);
168         if (man->meta.title)
169                 free(man->meta.title);
170         if (man->meta.source)
171                 free(man->meta.source);
172         if (man->meta.vol)
173                 free(man->meta.vol);
174 }
175
176
177 static void
178 man_alloc1(struct man *m)
179 {
180
181         memset(&m->meta, 0, sizeof(struct man_meta));
182         m->flags = 0;
183         m->last = mandoc_calloc(1, sizeof(struct man_node));
184         m->first = m->last;
185         m->last->type = MAN_ROOT;
186         m->last->tok = MAN_MAX;
187         m->next = MAN_NEXT_CHILD;
188 }
189
190
191 static int
192 man_node_append(struct man *man, struct man_node *p)
193 {
194
195         assert(man->last);
196         assert(man->first);
197         assert(MAN_ROOT != p->type);
198
199         switch (man->next) {
200         case (MAN_NEXT_SIBLING):
201                 man->last->next = p;
202                 p->prev = man->last;
203                 p->parent = man->last->parent;
204                 break;
205         case (MAN_NEXT_CHILD):
206                 man->last->child = p;
207                 p->parent = man->last;
208                 break;
209         default:
210                 abort();
211                 /* NOTREACHED */
212         }
213
214         assert(p->parent);
215         p->parent->nchild++;
216
217         if ( ! man_valid_pre(man, p))
218                 return(0);
219
220         switch (p->type) {
221         case (MAN_HEAD):
222                 assert(MAN_BLOCK == p->parent->type);
223                 p->parent->head = p;
224                 break;
225         case (MAN_BODY):
226                 assert(MAN_BLOCK == p->parent->type);
227                 p->parent->body = p;
228                 break;
229         default:
230                 break;
231         }
232
233         man->last = p;
234
235         switch (p->type) {
236         case (MAN_TEXT):
237                 if ( ! man_valid_post(man))
238                         return(0);
239                 if ( ! man_action_post(man))
240                         return(0);
241                 break;
242         default:
243                 break;
244         }
245
246         return(1);
247 }
248
249
250 static struct man_node *
251 man_node_alloc(int line, int pos, enum man_type type, enum mant tok)
252 {
253         struct man_node *p;
254
255         p = mandoc_calloc(1, sizeof(struct man_node));
256         p->line = line;
257         p->pos = pos;
258         p->type = type;
259         p->tok = tok;
260         return(p);
261 }
262
263
264 int
265 man_elem_alloc(struct man *m, int line, int pos, enum mant tok)
266 {
267         struct man_node *p;
268
269         p = man_node_alloc(line, pos, MAN_ELEM, tok);
270         if ( ! man_node_append(m, p))
271                 return(0);
272         m->next = MAN_NEXT_CHILD;
273         return(1);
274 }
275
276
277 int
278 man_head_alloc(struct man *m, int line, int pos, enum mant tok)
279 {
280         struct man_node *p;
281
282         p = man_node_alloc(line, pos, MAN_HEAD, tok);
283         if ( ! man_node_append(m, p))
284                 return(0);
285         m->next = MAN_NEXT_CHILD;
286         return(1);
287 }
288
289
290 int
291 man_body_alloc(struct man *m, int line, int pos, enum mant tok)
292 {
293         struct man_node *p;
294
295         p = man_node_alloc(line, pos, MAN_BODY, tok);
296         if ( ! man_node_append(m, p))
297                 return(0);
298         m->next = MAN_NEXT_CHILD;
299         return(1);
300 }
301
302
303 int
304 man_block_alloc(struct man *m, int line, int pos, enum mant tok)
305 {
306         struct man_node *p;
307
308         p = man_node_alloc(line, pos, MAN_BLOCK, tok);
309         if ( ! man_node_append(m, p))
310                 return(0);
311         m->next = MAN_NEXT_CHILD;
312         return(1);
313 }
314
315
316 static int
317 pstring(struct man *m, int line, int pos,
318                 const char *p, size_t len)
319 {
320         struct man_node *n;
321         size_t           sv;
322
323         n = man_node_alloc(line, pos, MAN_TEXT, MAN_MAX);
324         n->string = mandoc_malloc(len + 1);
325         sv = strlcpy(n->string, p, len + 1);
326
327         /* Prohibit truncation. */
328         assert(sv < len + 1);
329
330         if ( ! man_node_append(m, n))
331                 return(0);
332         m->next = MAN_NEXT_SIBLING;
333         return(1);
334 }
335
336
337 int
338 man_word_alloc(struct man *m, int line, int pos, const char *word)
339 {
340
341         return(pstring(m, line, pos, word, strlen(word)));
342 }
343
344
345 /*
346  * Free all of the resources held by a node.  This does NOT unlink a
347  * node from its context; for that, see man_node_unlink().
348  */
349 static void
350 man_node_free(struct man_node *p)
351 {
352
353         if (p->string)
354                 free(p->string);
355         free(p);
356 }
357
358
359 void
360 man_node_delete(struct man *m, struct man_node *p)
361 {
362
363         while (p->child)
364                 man_node_delete(m, p->child);
365
366         man_node_unlink(m, p);
367         man_node_free(p);
368 }
369
370
371 static int
372 man_ptext(struct man *m, int line, char *buf)
373 {
374         int              i, j;
375         char             sv;
376
377         /* Literal free-form text whitespace is preserved. */
378
379         if (MAN_LITERAL & m->flags) {
380                 if ( ! man_word_alloc(m, line, 0, buf))
381                         return(0);
382                 goto descope;
383         }
384
385         /* First de-chunk and allocate words. */
386
387         for (i = 0; ' ' == buf[i]; i++)
388                 /* Skip leading whitespace. */ ;
389
390         if ('\0' == buf[i]) {
391                 /* Trailing whitespace? */
392                 if (i && ' ' == buf[i - 1])
393                         if ( ! man_pwarn(m, line, i - 1, WTSPACE))
394                                 return(0);
395                 if ( ! pstring(m, line, 0, &buf[i], 0))
396                         return(0);
397                 goto descope;
398         }
399
400         for (j = i; buf[i]; i++) {
401                 if (' ' != buf[i])
402                         continue;
403
404                 /* Escaped whitespace. */
405                 if (i && ' ' == buf[i] && '\\' == buf[i - 1])
406                         continue;
407
408                 sv = buf[i];
409                 buf[i++] = '\0';
410
411                 if ( ! pstring(m, line, j, &buf[j], (size_t)(i - j)))
412                         return(0);
413
414                 /* Trailing whitespace?  Check at overwritten byte. */
415
416                 if (' ' == sv && '\0' == buf[i])
417                         if ( ! man_pwarn(m, line, i - 1, WTSPACE))
418                                 return(0);
419
420                 for ( ; ' ' == buf[i]; i++)
421                         /* Skip trailing whitespace. */ ;
422
423                 j = i;
424
425                 /* Trailing whitespace? */
426
427                 if (' ' == buf[i - 1] && '\0' == buf[i])
428                         if ( ! man_pwarn(m, line, i - 1, WTSPACE))
429                                 return(0);
430
431                 if ('\0' == buf[i])
432                         break;
433         }
434
435         if (j != i && ! pstring(m, line, j, &buf[j], (size_t)(i - j)))
436                 return(0);
437
438 descope:
439
440         /*
441          * Co-ordinate what happens with having a next-line scope open:
442          * first close out the element scope (if applicable), then close
443          * out the block scope (also if applicable).
444          */
445
446         if (MAN_ELINE & m->flags) {
447                 m->flags &= ~MAN_ELINE;
448                 if ( ! man_unscope(m, m->last->parent, WERRMAX))
449                         return(0);
450         }
451
452         if ( ! (MAN_BLINE & m->flags))
453                 return(1);
454         m->flags &= ~MAN_BLINE;
455
456         if ( ! man_unscope(m, m->last->parent, WERRMAX))
457                 return(0);
458         return(man_body_alloc(m, line, 0, m->last->tok));
459 }
460
461
462 static int
463 macrowarn(struct man *m, int ln, const char *buf)
464 {
465         if ( ! (MAN_IGN_MACRO & m->pflags))
466                 return(man_verr(m, ln, 0,
467                                 "unknown macro: %s%s",
468                                 buf, strlen(buf) > 3 ? "..." : ""));
469         return(man_vwarn(m, ln, 0, "unknown macro: %s%s",
470                                 buf, strlen(buf) > 3 ? "..." : ""));
471 }
472
473
474 int
475 man_pmacro(struct man *m, int ln, char *buf)
476 {
477         int              i, j, ppos;
478         enum mant        tok;
479         char             mac[5];
480         struct man_node *n;
481
482         /* Comments and empties are quickly ignored. */
483
484         if ('\0' == buf[1])
485                 return(1);
486
487         i = 1;
488
489         /*
490          * Skip whitespace between the control character and initial
491          * text.  "Whitespace" is both spaces and tabs.
492          */
493         if (' ' == buf[i] || '\t' == buf[i]) {
494                 i++;
495                 while (buf[i] && (' ' == buf[i] || '\t' == buf[i]))
496                         i++;
497                 if ('\0' == buf[i])
498                         goto out;
499         }
500
501         ppos = i;
502
503         /* Copy the first word into a nil-terminated buffer. */
504
505         for (j = 0; j < 4; j++, i++) {
506                 if ('\0' == (mac[j] = buf[i]))
507                         break;
508                 else if (' ' == buf[i])
509                         break;
510
511                 /* Check for invalid characters. */
512
513                 if (isgraph((u_char)buf[i]))
514                         continue;
515                 return(man_perr(m, ln, i, WNPRINT));
516         }
517
518         mac[j] = '\0';
519
520         if (j == 4 || j < 1) {
521                 if ( ! (MAN_IGN_MACRO & m->pflags)) {
522                         (void)man_perr(m, ln, ppos, WMACROFORM);
523                         goto err;
524                 }
525                 if ( ! man_pwarn(m, ln, ppos, WMACROFORM))
526                         goto err;
527                 return(1);
528         }
529
530         if (MAN_MAX == (tok = man_hash_find(mac))) {
531                 if ( ! macrowarn(m, ln, mac))
532                         goto err;
533                 return(1);
534         }
535
536         /* The macro is sane.  Jump to the next word. */
537
538         while (buf[i] && ' ' == buf[i])
539                 i++;
540
541         /* Trailing whitespace? */
542
543         if ('\0' == buf[i] && ' ' == buf[i - 1])
544                 if ( ! man_pwarn(m, ln, i - 1, WTSPACE))
545                         goto err;
546
547         /*
548          * Remove prior ELINE macro, as it's being clobbering by a new
549          * macro.  Note that NSCOPED macros do not close out ELINE
550          * macros---they don't print text---so we let those slip by.
551          * NOTE: we don't allow roff blocks (NOCLOSE) to be embedded
552          * here because that would stipulate blocks as children of
553          * elements!
554          */
555
556         if ( ! (MAN_NSCOPED & man_macros[tok].flags) &&
557                         m->flags & MAN_ELINE) {
558                 assert(MAN_TEXT != m->last->type);
559
560                 /*
561                  * This occurs in the following construction:
562                  *   .B
563                  *   .br
564                  *   .B
565                  *   .br
566                  *   I hate man macros.
567                  * Flat-out disallow this madness.
568                  */
569                 if (MAN_NSCOPED & man_macros[m->last->tok].flags)
570                         return(man_perr(m, ln, ppos, WLNSCOPE));
571
572                 n = m->last;
573
574                 assert(n);
575                 assert(NULL == n->child);
576                 assert(0 == n->nchild);
577
578                 if ( ! man_nwarn(m, n, WLNSCOPE))
579                         return(0);
580
581                 man_node_delete(m, n);
582                 m->flags &= ~MAN_ELINE;
583         }
584
585         /*
586          * Save the fact that we're in the next-line for a block.  In
587          * this way, embedded roff instructions can "remember" state
588          * when they exit.
589          */
590
591         if (MAN_BLINE & m->flags)
592                 m->flags |= MAN_BPLINE;
593
594         /* Call to handler... */
595
596         assert(man_macros[tok].fp);
597         if ( ! (*man_macros[tok].fp)(m, tok, ln, ppos, &i, buf))
598                 goto err;
599
600 out:
601         /*
602          * We weren't in a block-line scope when entering the
603          * above-parsed macro, so return.
604          */
605
606         if ( ! (MAN_BPLINE & m->flags)) {
607                 m->flags &= ~MAN_ILINE;
608                 return(1);
609         }
610         m->flags &= ~MAN_BPLINE;
611
612         /*
613          * If we're in a block scope, then allow this macro to slip by
614          * without closing scope around it.
615          */
616
617         if (MAN_ILINE & m->flags) {
618                 m->flags &= ~MAN_ILINE;
619                 return(1);
620         }
621
622         /*
623          * If we've opened a new next-line element scope, then return
624          * now, as the next line will close out the block scope.
625          */
626
627         if (MAN_ELINE & m->flags)
628                 return(1);
629
630         /* Close out the block scope opened in the prior line.  */
631
632         assert(MAN_BLINE & m->flags);
633         m->flags &= ~MAN_BLINE;
634
635         if ( ! man_unscope(m, m->last->parent, WERRMAX))
636                 return(0);
637         return(man_body_alloc(m, ln, 0, m->last->tok));
638
639 err:    /* Error out. */
640
641         m->flags |= MAN_HALT;
642         return(0);
643 }
644
645
646 int
647 man_verr(struct man *man, int ln, int pos, const char *fmt, ...)
648 {
649         char             buf[256];
650         va_list          ap;
651
652         if (NULL == man->cb.man_err)
653                 return(0);
654
655         va_start(ap, fmt);
656         (void)vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
657         va_end(ap);
658         return((*man->cb.man_err)(man->data, ln, pos, buf));
659 }
660
661
662 int
663 man_vwarn(struct man *man, int ln, int pos, const char *fmt, ...)
664 {
665         char             buf[256];
666         va_list          ap;
667
668         if (NULL == man->cb.man_warn)
669                 return(0);
670
671         va_start(ap, fmt);
672         (void)vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
673         va_end(ap);
674         return((*man->cb.man_warn)(man->data, ln, pos, buf));
675 }
676
677
678 int
679 man_err(struct man *m, int line, int pos, int iserr, enum merr type)
680 {
681         const char       *p;
682
683         p = __man_merrnames[(int)type];
684         assert(p);
685
686         if (iserr)
687                 return(man_verr(m, line, pos, p));
688
689         return(man_vwarn(m, line, pos, p));
690 }
691
692
693 /*
694  * Unlink a node from its context.  If "m" is provided, the last parse
695  * point will also be adjusted accordingly.
696  */
697 static void
698 man_node_unlink(struct man *m, struct man_node *n)
699 {
700
701         /* Adjust siblings. */
702
703         if (n->prev)
704                 n->prev->next = n->next;
705         if (n->next)
706                 n->next->prev = n->prev;
707
708         /* Adjust parent. */
709
710         if (n->parent) {
711                 n->parent->nchild--;
712                 if (n->parent->child == n)
713                         n->parent->child = n->prev ? n->prev : n->next;
714         }
715
716         /* Adjust parse point, if applicable. */
717
718         if (m && m->last == n) {
719                 /*XXX: this can occur when bailing from validation. */
720                 /*assert(NULL == n->next);*/
721                 if (n->prev) {
722                         m->last = n->prev;
723                         m->next = MAN_NEXT_SIBLING;
724                 } else {
725                         m->last = n->parent;
726                         m->next = MAN_NEXT_CHILD;
727                 }
728         }
729
730         if (m && m->first == n)
731                 m->first = NULL;
732 }