]> git.cameronkatri.com Git - mandoc.git/blob - roff.c
done: .de; todo: """"; loops in macro and string expansion
[mandoc.git] / roff.c
1 /* $Id: roff.c,v 1.107 2010/12/06 13:25:25 kristaps Exp $ */
2 /*
3 * Copyright (c) 2010 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2010 Ingo Schwarze <schwarze@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29
30 #include "mandoc.h"
31 #include "roff.h"
32 #include "libmandoc.h"
33
34 #define RSTACK_MAX 128
35
36 #define ROFF_CTL(c) \
37 ('.' == (c) || '\'' == (c))
38
39 #if 1
40 #define ROFF_DEBUG(fmt, args...) \
41 do { /* Nothing. */ } while (/*CONSTCOND*/ 0)
42 #else
43 #define ROFF_DEBUG(fmt, args...) \
44 do { fprintf(stderr, fmt , ##args); } while (/*CONSTCOND*/ 0)
45 #endif
46
47 enum rofft {
48 ROFF_ad,
49 ROFF_am,
50 ROFF_ami,
51 ROFF_am1,
52 ROFF_de,
53 ROFF_dei,
54 ROFF_de1,
55 ROFF_ds,
56 ROFF_el,
57 ROFF_hy,
58 ROFF_ie,
59 ROFF_if,
60 ROFF_ig,
61 ROFF_ne,
62 ROFF_nh,
63 ROFF_nr,
64 ROFF_rm,
65 ROFF_so,
66 ROFF_tr,
67 ROFF_cblock,
68 ROFF_ccond, /* FIXME: remove this. */
69 ROFF_USERDEF,
70 ROFF_MAX
71 };
72
73 enum roffrule {
74 ROFFRULE_ALLOW,
75 ROFFRULE_DENY
76 };
77
78
79 struct roffstr {
80 char *name; /* key of symbol */
81 char *string; /* current value */
82 struct roffstr *next; /* next in list */
83 };
84
85 struct roff {
86 struct roffnode *last; /* leaf of stack */
87 mandocmsg msg; /* err/warn/fatal messages */
88 void *data; /* privdata for messages */
89 enum roffrule rstack[RSTACK_MAX]; /* stack of !`ie' rules */
90 int rstackpos; /* position in rstack */
91 struct regset *regs; /* read/writable registers */
92 struct roffstr *first_string; /* user-defined strings & macros */
93 const char *current_string; /* value of last called user macro */
94 };
95
96 struct roffnode {
97 enum rofft tok; /* type of node */
98 struct roffnode *parent; /* up one in stack */
99 int line; /* parse line */
100 int col; /* parse col */
101 char *name; /* node name, e.g. macro name */
102 char *end; /* end-rules: custom token */
103 int endspan; /* end-rules: next-line or infty */
104 enum roffrule rule; /* current evaluation rule */
105 };
106
107 #define ROFF_ARGS struct roff *r, /* parse ctx */ \
108 enum rofft tok, /* tok of macro */ \
109 char **bufp, /* input buffer */ \
110 size_t *szp, /* size of input buffer */ \
111 int ln, /* parse line */ \
112 int ppos, /* original pos in buffer */ \
113 int pos, /* current pos in buffer */ \
114 int *offs /* reset offset of buffer data */
115
116 typedef enum rofferr (*roffproc)(ROFF_ARGS);
117
118 struct roffmac {
119 const char *name; /* macro name */
120 roffproc proc; /* process new macro */
121 roffproc text; /* process as child text of macro */
122 roffproc sub; /* process as child of macro */
123 int flags;
124 #define ROFFMAC_STRUCT (1 << 0) /* always interpret */
125 struct roffmac *next;
126 };
127
128 static enum rofferr roff_block(ROFF_ARGS);
129 static enum rofferr roff_block_text(ROFF_ARGS);
130 static enum rofferr roff_block_sub(ROFF_ARGS);
131 static enum rofferr roff_cblock(ROFF_ARGS);
132 static enum rofferr roff_ccond(ROFF_ARGS);
133 static enum rofferr roff_cond(ROFF_ARGS);
134 static enum rofferr roff_cond_text(ROFF_ARGS);
135 static enum rofferr roff_cond_sub(ROFF_ARGS);
136 static enum rofferr roff_ds(ROFF_ARGS);
137 static enum roffrule roff_evalcond(const char *, int *);
138 static void roff_freestr(struct roff *);
139 static const char *roff_getstrn(const struct roff *,
140 const char *, size_t);
141 static enum rofferr roff_line_ignore(ROFF_ARGS);
142 static enum rofferr roff_line_error(ROFF_ARGS);
143 static enum rofferr roff_nr(ROFF_ARGS);
144 static int roff_res(struct roff *,
145 char **, size_t *, int);
146 static void roff_setstr(struct roff *,
147 const char *, const char *, int);
148 static enum rofferr roff_so(ROFF_ARGS);
149 static enum rofferr roff_userdef(ROFF_ARGS);
150
151 /* See roff_hash_find() */
152
153 #define ASCII_HI 126
154 #define ASCII_LO 33
155 #define HASHWIDTH (ASCII_HI - ASCII_LO + 1)
156
157 static struct roffmac *hash[HASHWIDTH];
158
159 static struct roffmac roffs[ROFF_MAX] = {
160 { "ad", roff_line_ignore, NULL, NULL, 0, NULL },
161 { "am", roff_block, roff_block_text, roff_block_sub, 0, NULL },
162 { "ami", roff_block, roff_block_text, roff_block_sub, 0, NULL },
163 { "am1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
164 { "de", roff_block, roff_block_text, roff_block_sub, 0, NULL },
165 { "dei", roff_block, roff_block_text, roff_block_sub, 0, NULL },
166 { "de1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
167 { "ds", roff_ds, NULL, NULL, 0, NULL },
168 { "el", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
169 { "hy", roff_line_ignore, NULL, NULL, 0, NULL },
170 { "ie", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
171 { "if", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
172 { "ig", roff_block, roff_block_text, roff_block_sub, 0, NULL },
173 { "ne", roff_line_ignore, NULL, NULL, 0, NULL },
174 { "nh", roff_line_ignore, NULL, NULL, 0, NULL },
175 { "nr", roff_nr, NULL, NULL, 0, NULL },
176 { "rm", roff_line_error, NULL, NULL, 0, NULL },
177 { "so", roff_so, NULL, NULL, 0, NULL },
178 { "tr", roff_line_ignore, NULL, NULL, 0, NULL },
179 { ".", roff_cblock, NULL, NULL, 0, NULL },
180 { "\\}", roff_ccond, NULL, NULL, 0, NULL },
181 { NULL, roff_userdef, NULL, NULL, 0, NULL },
182 };
183
184 static void roff_free1(struct roff *);
185 static enum rofft roff_hash_find(const char *, size_t);
186 static void roff_hash_init(void);
187 static void roffnode_cleanscope(struct roff *);
188 static void roffnode_push(struct roff *, enum rofft,
189 const char *, int, int);
190 static void roffnode_pop(struct roff *);
191 static enum rofft roff_parse(struct roff *, const char *, int *);
192 static int roff_parse_nat(const char *, unsigned int *);
193
194 /* See roff_hash_find() */
195 #define ROFF_HASH(p) (p[0] - ASCII_LO)
196
197 static void
198 roff_hash_init(void)
199 {
200 struct roffmac *n;
201 int buc, i;
202
203 for (i = 0; i < (int)ROFF_USERDEF; i++) {
204 assert(roffs[i].name[0] >= ASCII_LO);
205 assert(roffs[i].name[0] <= ASCII_HI);
206
207 buc = ROFF_HASH(roffs[i].name);
208
209 if (NULL != (n = hash[buc])) {
210 for ( ; n->next; n = n->next)
211 /* Do nothing. */ ;
212 n->next = &roffs[i];
213 } else
214 hash[buc] = &roffs[i];
215 }
216 }
217
218
219 /*
220 * Look up a roff token by its name. Returns ROFF_MAX if no macro by
221 * the nil-terminated string name could be found.
222 */
223 static enum rofft
224 roff_hash_find(const char *p, size_t s)
225 {
226 int buc;
227 struct roffmac *n;
228
229 /*
230 * libroff has an extremely simple hashtable, for the time
231 * being, which simply keys on the first character, which must
232 * be printable, then walks a chain. It works well enough until
233 * optimised.
234 */
235
236 if (p[0] < ASCII_LO || p[0] > ASCII_HI)
237 return(ROFF_MAX);
238
239 buc = ROFF_HASH(p);
240
241 if (NULL == (n = hash[buc]))
242 return(ROFF_MAX);
243 for ( ; n; n = n->next)
244 if (0 == strncmp(n->name, p, s) && '\0' == n->name[(int)s])
245 return((enum rofft)(n - roffs));
246
247 return(ROFF_MAX);
248 }
249
250
251 /*
252 * Pop the current node off of the stack of roff instructions currently
253 * pending.
254 */
255 static void
256 roffnode_pop(struct roff *r)
257 {
258 struct roffnode *p;
259
260 assert(r->last);
261 p = r->last;
262
263 if (ROFF_el == p->tok)
264 if (r->rstackpos > -1)
265 r->rstackpos--;
266
267 ROFF_DEBUG("roff: popping scope\n");
268 r->last = r->last->parent;
269 free(p->name);
270 free(p->end);
271 free(p);
272 }
273
274
275 /*
276 * Push a roff node onto the instruction stack. This must later be
277 * removed with roffnode_pop().
278 */
279 static void
280 roffnode_push(struct roff *r, enum rofft tok, const char *name,
281 int line, int col)
282 {
283 struct roffnode *p;
284
285 p = mandoc_calloc(1, sizeof(struct roffnode));
286 p->tok = tok;
287 if (name)
288 p->name = mandoc_strdup(name);
289 p->parent = r->last;
290 p->line = line;
291 p->col = col;
292 p->rule = p->parent ? p->parent->rule : ROFFRULE_DENY;
293
294 r->last = p;
295 }
296
297
298 static void
299 roff_free1(struct roff *r)
300 {
301
302 while (r->last)
303 roffnode_pop(r);
304 roff_freestr(r);
305 }
306
307
308 void
309 roff_reset(struct roff *r)
310 {
311
312 roff_free1(r);
313 }
314
315
316 void
317 roff_free(struct roff *r)
318 {
319
320 roff_free1(r);
321 free(r);
322 }
323
324
325 struct roff *
326 roff_alloc(struct regset *regs, void *data, const mandocmsg msg)
327 {
328 struct roff *r;
329
330 r = mandoc_calloc(1, sizeof(struct roff));
331 r->regs = regs;
332 r->msg = msg;
333 r->data = data;
334 r->rstackpos = -1;
335
336 roff_hash_init();
337 return(r);
338 }
339
340
341 /*
342 * Pre-filter each and every line for reserved words (one beginning with
343 * `\*', e.g., `\*(ab'). These must be handled before the actual line
344 * is processed.
345 */
346 static int
347 roff_res(struct roff *r, char **bufp, size_t *szp, int pos)
348 {
349 const char *cp, *cpp, *st, *res;
350 int i, maxl;
351 size_t nsz;
352 char *n;
353
354 /* LINTED */
355 for (cp = &(*bufp)[pos]; (cpp = strstr(cp, "\\*")); cp++) {
356 cp = cpp + 2;
357 switch (*cp) {
358 case ('('):
359 cp++;
360 maxl = 2;
361 break;
362 case ('['):
363 cp++;
364 maxl = 0;
365 break;
366 default:
367 maxl = 1;
368 break;
369 }
370
371 st = cp;
372
373 for (i = 0; 0 == maxl || i < maxl; i++, cp++) {
374 if ('\0' == *cp)
375 return(1); /* Error. */
376 if (0 == maxl && ']' == *cp)
377 break;
378 }
379
380 res = roff_getstrn(r, st, (size_t)i);
381
382 if (NULL == res) {
383 cp -= maxl ? 1 : 0;
384 continue;
385 }
386
387 ROFF_DEBUG("roff: splicing reserved: [%.*s]\n", i, st);
388
389 nsz = *szp + strlen(res) + 1;
390 n = mandoc_malloc(nsz);
391
392 *n = '\0';
393
394 strlcat(n, *bufp, (size_t)(cpp - *bufp + 1));
395 strlcat(n, res, nsz);
396 strlcat(n, cp + (maxl ? 0 : 1), nsz);
397
398 free(*bufp);
399
400 *bufp = n;
401 *szp = nsz;
402 return(0);
403 }
404
405 return(1);
406 }
407
408
409 enum rofferr
410 roff_parseln(struct roff *r, int ln, char **bufp,
411 size_t *szp, int pos, int *offs)
412 {
413 enum rofft t;
414 int ppos;
415
416 /*
417 * Run the reserved-word filter only if we have some reserved
418 * words to fill in.
419 */
420
421 if (r->first_string && ! roff_res(r, bufp, szp, pos))
422 return(ROFF_REPARSE);
423
424 /*
425 * First, if a scope is open and we're not a macro, pass the
426 * text through the macro's filter. If a scope isn't open and
427 * we're not a macro, just let it through.
428 */
429
430 if (r->last && ! ROFF_CTL((*bufp)[pos])) {
431 t = r->last->tok;
432 assert(roffs[t].text);
433 ROFF_DEBUG("roff: intercept scoped text: %s, [%s]\n",
434 roffs[t].name, &(*bufp)[pos]);
435 return((*roffs[t].text)
436 (r, t, bufp, szp,
437 ln, pos, pos, offs));
438 } else if ( ! ROFF_CTL((*bufp)[pos]))
439 return(ROFF_CONT);
440
441 /*
442 * If a scope is open, go to the child handler for that macro,
443 * as it may want to preprocess before doing anything with it.
444 */
445
446 if (r->last) {
447 t = r->last->tok;
448 assert(roffs[t].sub);
449 ROFF_DEBUG("roff: intercept scoped context: %s, [%s]\n",
450 roffs[t].name, &(*bufp)[pos]);
451 return((*roffs[t].sub)
452 (r, t, bufp, szp,
453 ln, pos, pos, offs));
454 }
455
456 /*
457 * Lastly, as we've no scope open, try to look up and execute
458 * the new macro. If no macro is found, simply return and let
459 * the compilers handle it.
460 */
461
462 ppos = pos;
463 if (ROFF_MAX == (t = roff_parse(r, *bufp, &pos)))
464 return(ROFF_CONT);
465
466 ROFF_DEBUG("roff: intercept new-scope: [%s], [%s]\n",
467 ROFF_USERDEF == t ? r->current_string : roffs[t].name,
468 &(*bufp)[pos]);
469
470 assert(roffs[t].proc);
471 return((*roffs[t].proc)
472 (r, t, bufp, szp,
473 ln, ppos, pos, offs));
474 }
475
476
477 int
478 roff_endparse(struct roff *r)
479 {
480
481 if (NULL == r->last)
482 return(1);
483 return((*r->msg)(MANDOCERR_SCOPEEXIT, r->data, r->last->line,
484 r->last->col, NULL));
485 }
486
487
488 /*
489 * Parse a roff node's type from the input buffer. This must be in the
490 * form of ".foo xxx" in the usual way.
491 */
492 static enum rofft
493 roff_parse(struct roff *r, const char *buf, int *pos)
494 {
495 const char *mac;
496 size_t maclen;
497 enum rofft t;
498
499 assert(ROFF_CTL(buf[*pos]));
500 (*pos)++;
501
502 while (' ' == buf[*pos] || '\t' == buf[*pos])
503 (*pos)++;
504
505 if ('\0' == buf[*pos])
506 return(ROFF_MAX);
507
508 mac = buf + *pos;
509 maclen = strcspn(mac, " \\\t\0");
510
511 t = (r->current_string = roff_getstrn(r, mac, maclen))
512 ? ROFF_USERDEF : roff_hash_find(mac, maclen);
513
514 *pos += maclen;
515 while (buf[*pos] && ' ' == buf[*pos])
516 (*pos)++;
517
518 return(t);
519 }
520
521
522 static int
523 roff_parse_nat(const char *buf, unsigned int *res)
524 {
525 char *ep;
526 long lval;
527
528 errno = 0;
529 lval = strtol(buf, &ep, 10);
530 if (buf[0] == '\0' || *ep != '\0')
531 return(0);
532 if ((errno == ERANGE &&
533 (lval == LONG_MAX || lval == LONG_MIN)) ||
534 (lval > INT_MAX || lval < 0))
535 return(0);
536
537 *res = (unsigned int)lval;
538 return(1);
539 }
540
541
542 /* ARGSUSED */
543 static enum rofferr
544 roff_cblock(ROFF_ARGS)
545 {
546
547 /*
548 * A block-close `..' should only be invoked as a child of an
549 * ignore macro, otherwise raise a warning and just ignore it.
550 */
551
552 if (NULL == r->last) {
553 if ( ! (*r->msg)(MANDOCERR_NOSCOPE, r->data, ln, ppos, NULL))
554 return(ROFF_ERR);
555 return(ROFF_IGN);
556 }
557
558 switch (r->last->tok) {
559 case (ROFF_am):
560 /* FALLTHROUGH */
561 case (ROFF_ami):
562 /* FALLTHROUGH */
563 case (ROFF_am1):
564 /* FALLTHROUGH */
565 case (ROFF_de):
566 /* FALLTHROUGH */
567 case (ROFF_dei):
568 /* FALLTHROUGH */
569 case (ROFF_ig):
570 break;
571 default:
572 if ( ! (*r->msg)(MANDOCERR_NOSCOPE, r->data, ln, ppos, NULL))
573 return(ROFF_ERR);
574 return(ROFF_IGN);
575 }
576
577 if ((*bufp)[pos])
578 if ( ! (*r->msg)(MANDOCERR_ARGSLOST, r->data, ln, pos, NULL))
579 return(ROFF_ERR);
580
581 roffnode_pop(r);
582 roffnode_cleanscope(r);
583 return(ROFF_IGN);
584
585 }
586
587
588 static void
589 roffnode_cleanscope(struct roff *r)
590 {
591
592 while (r->last) {
593 if (--r->last->endspan < 0)
594 break;
595 roffnode_pop(r);
596 }
597 }
598
599
600 /* ARGSUSED */
601 static enum rofferr
602 roff_ccond(ROFF_ARGS)
603 {
604
605 if (NULL == r->last) {
606 if ( ! (*r->msg)(MANDOCERR_NOSCOPE, r->data, ln, ppos, NULL))
607 return(ROFF_ERR);
608 return(ROFF_IGN);
609 }
610
611 switch (r->last->tok) {
612 case (ROFF_el):
613 /* FALLTHROUGH */
614 case (ROFF_ie):
615 /* FALLTHROUGH */
616 case (ROFF_if):
617 break;
618 default:
619 if ( ! (*r->msg)(MANDOCERR_NOSCOPE, r->data, ln, ppos, NULL))
620 return(ROFF_ERR);
621 return(ROFF_IGN);
622 }
623
624 if (r->last->endspan > -1) {
625 if ( ! (*r->msg)(MANDOCERR_NOSCOPE, r->data, ln, ppos, NULL))
626 return(ROFF_ERR);
627 return(ROFF_IGN);
628 }
629
630 if ((*bufp)[pos])
631 if ( ! (*r->msg)(MANDOCERR_ARGSLOST, r->data, ln, pos, NULL))
632 return(ROFF_ERR);
633
634 roffnode_pop(r);
635 roffnode_cleanscope(r);
636 return(ROFF_IGN);
637 }
638
639
640 /* ARGSUSED */
641 static enum rofferr
642 roff_block(ROFF_ARGS)
643 {
644 int sv;
645 size_t sz;
646 char *name;
647
648 name = NULL;
649
650 if (ROFF_ig != tok) {
651 if ('\0' == (*bufp)[pos]) {
652 (*r->msg)(MANDOCERR_NOARGS, r->data, ln, ppos, NULL);
653 return(ROFF_IGN);
654 }
655
656 /*
657 * Re-write `de1', since we don't really care about
658 * groff's strange compatibility mode, into `de'.
659 */
660
661 if (ROFF_de1 == tok)
662 tok = ROFF_de;
663 if (ROFF_de == tok)
664 name = *bufp + pos;
665 else
666 (*r->msg)(MANDOCERR_REQUEST, r->data, ln, ppos,
667 roffs[tok].name);
668
669 while ((*bufp)[pos] && ' ' != (*bufp)[pos])
670 pos++;
671
672 while (' ' == (*bufp)[pos])
673 (*bufp)[pos++] = '\0';
674 }
675
676 roffnode_push(r, tok, name, ln, ppos);
677
678 /*
679 * At the beginning of a `de' macro, clear the existing string
680 * with the same name, if there is one. New content will be
681 * added from roff_block_text() in multiline mode.
682 */
683
684 if (ROFF_de == tok)
685 roff_setstr(r, name, NULL, 0);
686
687 if ('\0' == (*bufp)[pos])
688 return(ROFF_IGN);
689
690 /* If present, process the custom end-of-line marker. */
691
692 sv = pos;
693 while ((*bufp)[pos] &&
694 ' ' != (*bufp)[pos] &&
695 '\t' != (*bufp)[pos])
696 pos++;
697
698 /*
699 * Note: groff does NOT like escape characters in the input.
700 * Instead of detecting this, we're just going to let it fly and
701 * to hell with it.
702 */
703
704 assert(pos > sv);
705 sz = (size_t)(pos - sv);
706
707 if (1 == sz && '.' == (*bufp)[sv])
708 return(ROFF_IGN);
709
710 r->last->end = mandoc_malloc(sz + 1);
711
712 memcpy(r->last->end, *bufp + sv, sz);
713 r->last->end[(int)sz] = '\0';
714
715 if ((*bufp)[pos])
716 (*r->msg)(MANDOCERR_ARGSLOST, r->data, ln, pos, NULL);
717
718 return(ROFF_IGN);
719 }
720
721
722 /* ARGSUSED */
723 static enum rofferr
724 roff_block_sub(ROFF_ARGS)
725 {
726 enum rofft t;
727 int i, j;
728
729 /*
730 * First check whether a custom macro exists at this level. If
731 * it does, then check against it. This is some of groff's
732 * stranger behaviours. If we encountered a custom end-scope
733 * tag and that tag also happens to be a "real" macro, then we
734 * need to try interpreting it again as a real macro. If it's
735 * not, then return ignore. Else continue.
736 */
737
738 if (r->last->end) {
739 i = pos + 1;
740 while (' ' == (*bufp)[i] || '\t' == (*bufp)[i])
741 i++;
742
743 for (j = 0; r->last->end[j]; j++, i++)
744 if ((*bufp)[i] != r->last->end[j])
745 break;
746
747 if ('\0' == r->last->end[j] &&
748 ('\0' == (*bufp)[i] ||
749 ' ' == (*bufp)[i] ||
750 '\t' == (*bufp)[i])) {
751 roffnode_pop(r);
752 roffnode_cleanscope(r);
753
754 if (ROFF_MAX != roff_parse(r, *bufp, &pos))
755 return(ROFF_RERUN);
756 return(ROFF_IGN);
757 }
758 }
759
760 /*
761 * If we have no custom end-query or lookup failed, then try
762 * pulling it out of the hashtable.
763 */
764
765 ppos = pos;
766 t = roff_parse(r, *bufp, &pos);
767
768 /*
769 * Macros other than block-end are only significant
770 * in `de' blocks; elsewhere, simply throw them away.
771 */
772 if (ROFF_cblock != t) {
773 if (ROFF_de == tok)
774 roff_setstr(r, r->last->name, *bufp + ppos, 1);
775 return(ROFF_IGN);
776 }
777
778 assert(roffs[t].proc);
779 return((*roffs[t].proc)(r, t, bufp, szp,
780 ln, ppos, pos, offs));
781 }
782
783
784 /* ARGSUSED */
785 static enum rofferr
786 roff_block_text(ROFF_ARGS)
787 {
788
789 if (ROFF_de == tok)
790 roff_setstr(r, r->last->name, *bufp + pos, 1);
791
792 return(ROFF_IGN);
793 }
794
795
796 /* ARGSUSED */
797 static enum rofferr
798 roff_cond_sub(ROFF_ARGS)
799 {
800 enum rofft t;
801 enum roffrule rr;
802
803 ppos = pos;
804 rr = r->last->rule;
805
806 /*
807 * Clean out scope. If we've closed ourselves, then don't
808 * continue.
809 */
810
811 roffnode_cleanscope(r);
812
813 if (ROFF_MAX == (t = roff_parse(r, *bufp, &pos))) {
814 if ('\\' == (*bufp)[pos] && '}' == (*bufp)[pos + 1])
815 return(roff_ccond
816 (r, ROFF_ccond, bufp, szp,
817 ln, pos, pos + 2, offs));
818 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
819 }
820
821 /*
822 * A denied conditional must evaluate its children if and only
823 * if they're either structurally required (such as loops and
824 * conditionals) or a closing macro.
825 */
826 if (ROFFRULE_DENY == rr)
827 if ( ! (ROFFMAC_STRUCT & roffs[t].flags))
828 if (ROFF_ccond != t)
829 return(ROFF_IGN);
830
831 assert(roffs[t].proc);
832 return((*roffs[t].proc)(r, t, bufp, szp,
833 ln, ppos, pos, offs));
834 }
835
836
837 /* ARGSUSED */
838 static enum rofferr
839 roff_cond_text(ROFF_ARGS)
840 {
841 char *ep, *st;
842 enum roffrule rr;
843
844 rr = r->last->rule;
845
846 /*
847 * We display the value of the text if out current evaluation
848 * scope permits us to do so.
849 */
850
851 /* FIXME: use roff_ccond? */
852
853 st = &(*bufp)[pos];
854 if (NULL == (ep = strstr(st, "\\}"))) {
855 roffnode_cleanscope(r);
856 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
857 }
858
859 if (ep == st || (ep > st && '\\' != *(ep - 1)))
860 roffnode_pop(r);
861
862 roffnode_cleanscope(r);
863 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
864 }
865
866
867 static enum roffrule
868 roff_evalcond(const char *v, int *pos)
869 {
870
871 switch (v[*pos]) {
872 case ('n'):
873 (*pos)++;
874 return(ROFFRULE_ALLOW);
875 case ('e'):
876 /* FALLTHROUGH */
877 case ('o'):
878 /* FALLTHROUGH */
879 case ('t'):
880 (*pos)++;
881 return(ROFFRULE_DENY);
882 default:
883 break;
884 }
885
886 while (v[*pos] && ' ' != v[*pos])
887 (*pos)++;
888 return(ROFFRULE_DENY);
889 }
890
891 /* ARGSUSED */
892 static enum rofferr
893 roff_line_ignore(ROFF_ARGS)
894 {
895
896 return(ROFF_IGN);
897 }
898
899 /* ARGSUSED */
900 static enum rofferr
901 roff_line_error(ROFF_ARGS)
902 {
903
904 (*r->msg)(MANDOCERR_REQUEST, r->data, ln, ppos, roffs[tok].name);
905 return(ROFF_IGN);
906 }
907
908 /* ARGSUSED */
909 static enum rofferr
910 roff_cond(ROFF_ARGS)
911 {
912 int sv;
913 enum roffrule rule;
914
915 /* Stack overflow! */
916
917 if (ROFF_ie == tok && r->rstackpos == RSTACK_MAX - 1) {
918 (*r->msg)(MANDOCERR_MEM, r->data, ln, ppos, NULL);
919 return(ROFF_ERR);
920 }
921
922 /* First, evaluate the conditional. */
923
924 if (ROFF_el == tok) {
925 /*
926 * An `.el' will get the value of the current rstack
927 * entry set in prior `ie' calls or defaults to DENY.
928 */
929 if (r->rstackpos < 0)
930 rule = ROFFRULE_DENY;
931 else
932 rule = r->rstack[r->rstackpos];
933 } else
934 rule = roff_evalcond(*bufp, &pos);
935
936 sv = pos;
937
938 while (' ' == (*bufp)[pos])
939 pos++;
940
941 /*
942 * Roff is weird. If we have just white-space after the
943 * conditional, it's considered the BODY and we exit without
944 * really doing anything. Warn about this. It's probably
945 * wrong.
946 */
947
948 if ('\0' == (*bufp)[pos] && sv != pos) {
949 (*r->msg)(MANDOCERR_NOARGS, r->data, ln, ppos, NULL);
950 return(ROFF_IGN);
951 }
952
953 roffnode_push(r, tok, NULL, ln, ppos);
954
955 r->last->rule = rule;
956
957 ROFF_DEBUG("roff: cond: %s -> %s\n", roffs[tok].name,
958 ROFFRULE_ALLOW == rule ? "allow" : "deny");
959
960 if (ROFF_ie == tok) {
961 /*
962 * An if-else will put the NEGATION of the current
963 * evaluated conditional into the stack.
964 */
965 r->rstackpos++;
966 if (ROFFRULE_DENY == r->last->rule)
967 r->rstack[r->rstackpos] = ROFFRULE_ALLOW;
968 else
969 r->rstack[r->rstackpos] = ROFFRULE_DENY;
970 }
971
972 /* If the parent has false as its rule, then so do we. */
973
974 if (r->last->parent && ROFFRULE_DENY == r->last->parent->rule) {
975 r->last->rule = ROFFRULE_DENY;
976 ROFF_DEBUG("roff: cond override: %s -> deny\n",
977 roffs[tok].name);
978 }
979
980 /*
981 * Determine scope. If we're invoked with "\{" trailing the
982 * conditional, then we're in a multiline scope. Else our scope
983 * expires on the next line.
984 */
985
986 r->last->endspan = 1;
987
988 if ('\\' == (*bufp)[pos] && '{' == (*bufp)[pos + 1]) {
989 r->last->endspan = -1;
990 pos += 2;
991 ROFF_DEBUG("roff: cond-scope: %s, multi-line\n",
992 roffs[tok].name);
993 } else
994 ROFF_DEBUG("roff: cond-scope: %s, one-line\n",
995 roffs[tok].name);
996
997 /*
998 * If there are no arguments on the line, the next-line scope is
999 * assumed.
1000 */
1001
1002 if ('\0' == (*bufp)[pos])
1003 return(ROFF_IGN);
1004
1005 /* Otherwise re-run the roff parser after recalculating. */
1006
1007 *offs = pos;
1008 return(ROFF_RERUN);
1009 }
1010
1011
1012 /* ARGSUSED */
1013 static enum rofferr
1014 roff_ds(ROFF_ARGS)
1015 {
1016 char *name, *string;
1017
1018 /*
1019 * A symbol is named by the first word following the macro
1020 * invocation up to a space. Its value is anything after the
1021 * name's trailing whitespace and optional double-quote. Thus,
1022 *
1023 * [.ds foo "bar " ]
1024 *
1025 * will have `bar " ' as its value.
1026 */
1027
1028 name = *bufp + pos;
1029 if ('\0' == *name)
1030 return(ROFF_IGN);
1031
1032 string = name;
1033 /* Read until end of name. */
1034 while (*string && ' ' != *string)
1035 string++;
1036
1037 /* Nil-terminate name. */
1038 if (*string)
1039 *(string++) = '\0';
1040
1041 /* Read past spaces. */
1042 while (*string && ' ' == *string)
1043 string++;
1044
1045 /* Read passed initial double-quote. */
1046 if (*string && '"' == *string)
1047 string++;
1048
1049 /* The rest is the value. */
1050 roff_setstr(r, name, string, 0);
1051 return(ROFF_IGN);
1052 }
1053
1054
1055 /* ARGSUSED */
1056 static enum rofferr
1057 roff_nr(ROFF_ARGS)
1058 {
1059 const char *key, *val;
1060 struct reg *rg;
1061
1062 key = &(*bufp)[pos];
1063 rg = r->regs->regs;
1064
1065 /* Parse register request. */
1066 while ((*bufp)[pos] && ' ' != (*bufp)[pos])
1067 pos++;
1068
1069 /*
1070 * Set our nil terminator. Because this line is going to be
1071 * ignored anyway, we can munge it as we please.
1072 */
1073 if ((*bufp)[pos])
1074 (*bufp)[pos++] = '\0';
1075
1076 /* Skip whitespace to register token. */
1077 while ((*bufp)[pos] && ' ' == (*bufp)[pos])
1078 pos++;
1079
1080 val = &(*bufp)[pos];
1081
1082 /* Process register token. */
1083
1084 if (0 == strcmp(key, "nS")) {
1085 rg[(int)REG_nS].set = 1;
1086 if ( ! roff_parse_nat(val, &rg[(int)REG_nS].v.u))
1087 rg[(int)REG_nS].v.u = 0;
1088
1089 ROFF_DEBUG("roff: register nS: %u\n",
1090 rg[(int)REG_nS].v.u);
1091 } else
1092 ROFF_DEBUG("roff: ignoring register: %s\n", key);
1093
1094 return(ROFF_IGN);
1095 }
1096
1097 /* ARGSUSED */
1098 static enum rofferr
1099 roff_so(ROFF_ARGS)
1100 {
1101 char *name;
1102
1103 (*r->msg)(MANDOCERR_SO, r->data, ln, ppos, NULL);
1104
1105 /*
1106 * Handle `so'. Be EXTREMELY careful, as we shouldn't be
1107 * opening anything that's not in our cwd or anything beneath
1108 * it. Thus, explicitly disallow traversing up the file-system
1109 * or using absolute paths.
1110 */
1111
1112 name = *bufp + pos;
1113 if ('/' == *name || strstr(name, "../") || strstr(name, "/..")) {
1114 (*r->msg)(MANDOCERR_SOPATH, r->data, ln, pos, NULL);
1115 return(ROFF_ERR);
1116 }
1117
1118 *offs = pos;
1119 return(ROFF_SO);
1120 }
1121
1122 /* ARGSUSED */
1123 static enum rofferr
1124 roff_userdef(ROFF_ARGS)
1125 {
1126 const char *arg[9];
1127 char *cp, *n1, *n2;
1128 int i, quoted, pairs;
1129
1130 /*
1131 * Collect pointers to macro argument strings
1132 * and null-terminate them.
1133 */
1134 cp = *bufp + pos;
1135 for (i = 0; i < 9; i++) {
1136 /* Quoting can only start with a new word. */
1137 if ('"' == *cp) {
1138 quoted = 1;
1139 cp++;
1140 } else
1141 quoted = 0;
1142 arg[i] = cp;
1143 for (pairs = 0; '\0' != *cp; cp++) {
1144 /* Unquoted arguments end at blanks. */
1145 if (0 == quoted) {
1146 if (' ' == *cp)
1147 break;
1148 continue;
1149 }
1150 /* After pairs of quotes, move left. */
1151 if (pairs)
1152 cp[-pairs] = cp[0];
1153 /* Pairs of quotes do not end words, ... */
1154 if ('"' == cp[0] && '"' == cp[1]) {
1155 pairs++;
1156 cp++;
1157 continue;
1158 }
1159 /* ... but solitary quotes do. */
1160 if ('"' != *cp)
1161 continue;
1162 if (pairs)
1163 cp[-pairs] = '\0';
1164 *cp = ' ';
1165 break;
1166 }
1167 /* Last argument; the remaining ones are empty strings. */
1168 if ('\0' == *cp)
1169 continue;
1170 /* Null-terminate argument and move to the next one. */
1171 *cp++ = '\0';
1172 while (' ' == *cp)
1173 cp++;
1174 }
1175
1176 /*
1177 * Expand macro arguments.
1178 */
1179 *szp = 0;
1180 n1 = cp = mandoc_strdup(r->current_string);
1181 while (NULL != (cp = strstr(cp, "\\$"))) {
1182 i = cp[2] - '1';
1183 if (0 > i || 8 < i) {
1184 /* Not an argument invocation. */
1185 cp += 2;
1186 continue;
1187 }
1188
1189 *szp = strlen(n1) - 3 + strlen(arg[i]) + 1;
1190 n2 = mandoc_malloc(*szp);
1191
1192 strlcpy(n2, n1, (size_t)(cp - n1 + 1));
1193 strlcat(n2, arg[i], *szp);
1194 strlcat(n2, cp + 3, *szp);
1195
1196 cp = n2 + (cp - n1);
1197 free(n1);
1198 n1 = n2;
1199 }
1200
1201 /*
1202 * Replace the macro invocation
1203 * by the expanded macro.
1204 */
1205 free(*bufp);
1206 *bufp = n1;
1207 if (0 == *szp)
1208 *szp = strlen(*bufp) + 1;
1209
1210 return(*szp > 1 && '\n' == (*bufp)[(int)*szp - 2] ?
1211 ROFF_REPARSE : ROFF_APPEND);
1212 }
1213
1214 /*
1215 * Store *string into the user-defined string called *name.
1216 * In multiline mode, append to an existing entry and append '\n';
1217 * else replace the existing entry, if there is one.
1218 * To clear an existing entry, call with (*r, *name, NULL, 0).
1219 */
1220 static void
1221 roff_setstr(struct roff *r, const char *name, const char *string,
1222 int multiline)
1223 {
1224 struct roffstr *n;
1225 char *c;
1226 size_t oldch, newch;
1227
1228 /* Search for an existing string with the same name. */
1229 n = r->first_string;
1230 while (n && strcmp(name, n->name))
1231 n = n->next;
1232
1233 if (NULL == n) {
1234 /* Create a new string table entry. */
1235 n = mandoc_malloc(sizeof(struct roffstr));
1236 n->name = mandoc_strdup(name);
1237 n->string = NULL;
1238 n->next = r->first_string;
1239 r->first_string = n;
1240 } else if (0 == multiline) {
1241 /* In multiline mode, append; else replace. */
1242 free(n->string);
1243 n->string = NULL;
1244 }
1245
1246 if (NULL == string)
1247 return;
1248
1249 /*
1250 * One additional byte for the '\n' in multiline mode,
1251 * and one for the terminating '\0'.
1252 */
1253 newch = strlen(string) + (multiline ? 2 : 1);
1254 if (NULL == n->string) {
1255 n->string = mandoc_malloc(newch);
1256 *n->string = '\0';
1257 oldch = 0;
1258 } else {
1259 oldch = strlen(n->string);
1260 n->string = mandoc_realloc(n->string, oldch + newch);
1261 }
1262
1263 /* Skip existing content in the destination buffer. */
1264 c = n->string + oldch;
1265
1266 /* Append new content to the destination buffer. */
1267 while (*string) {
1268 /*
1269 * Rudimentary roff copy mode:
1270 * Handle escaped backslashes.
1271 */
1272 if ('\\' == *string && '\\' == *(string + 1))
1273 string++;
1274 *c++ = *string++;
1275 }
1276
1277 /* Append terminating bytes. */
1278 if (multiline)
1279 *c++ = '\n';
1280 *c = '\0';
1281 }
1282
1283
1284 static const char *
1285 roff_getstrn(const struct roff *r, const char *name, size_t len)
1286 {
1287 const struct roffstr *n;
1288
1289 n = r->first_string;
1290 while (n && (strncmp(name, n->name, len) || '\0' != n->name[(int)len]))
1291 n = n->next;
1292
1293 return(n ? n->string : NULL);
1294 }
1295
1296
1297 static void
1298 roff_freestr(struct roff *r)
1299 {
1300 struct roffstr *n, *nn;
1301
1302 for (n = r->first_string; n; n = nn) {
1303 free(n->name);
1304 free(n->string);
1305 nn = n->next;
1306 free(n);
1307 }
1308
1309 r->first_string = NULL;
1310 }