]> git.cameronkatri.com Git - mandoc.git/blob - roff.c
Parse for the closing delimiter `\}' for conditionals
[mandoc.git] / roff.c
1 /* $Id: roff.c,v 1.177 2013/06/27 09:49:47 schwarze Exp $ */
2 /*
3 * Copyright (c) 2010, 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2010, 2011, 2012, 2013 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 <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "mandoc.h"
28 #include "libroff.h"
29 #include "libmandoc.h"
30
31 /* Maximum number of nested if-else conditionals. */
32 #define RSTACK_MAX 128
33
34 /* Maximum number of string expansions per line, to break infinite loops. */
35 #define EXPAND_LIMIT 1000
36
37 enum rofft {
38 ROFF_ad,
39 ROFF_am,
40 ROFF_ami,
41 ROFF_am1,
42 ROFF_cc,
43 ROFF_de,
44 ROFF_dei,
45 ROFF_de1,
46 ROFF_ds,
47 ROFF_el,
48 ROFF_hy,
49 ROFF_ie,
50 ROFF_if,
51 ROFF_ig,
52 ROFF_it,
53 ROFF_ne,
54 ROFF_nh,
55 ROFF_nr,
56 ROFF_ns,
57 ROFF_ps,
58 ROFF_rm,
59 ROFF_so,
60 ROFF_ta,
61 ROFF_tr,
62 ROFF_Dd,
63 ROFF_TH,
64 ROFF_TS,
65 ROFF_TE,
66 ROFF_T_,
67 ROFF_EQ,
68 ROFF_EN,
69 ROFF_cblock,
70 ROFF_ccond,
71 ROFF_USERDEF,
72 ROFF_MAX
73 };
74
75 enum roffrule {
76 ROFFRULE_ALLOW,
77 ROFFRULE_DENY
78 };
79
80 /*
81 * A single register entity. If "set" is zero, the value of the
82 * register should be the default one, which is per-register.
83 * Registers are assumed to be unsigned ints for now.
84 */
85 struct reg {
86 int set; /* whether set or not */
87 unsigned int u; /* unsigned integer */
88 };
89
90 /*
91 * An incredibly-simple string buffer.
92 */
93 struct roffstr {
94 char *p; /* nil-terminated buffer */
95 size_t sz; /* saved strlen(p) */
96 };
97
98 /*
99 * A key-value roffstr pair as part of a singly-linked list.
100 */
101 struct roffkv {
102 struct roffstr key;
103 struct roffstr val;
104 struct roffkv *next; /* next in list */
105 };
106
107 struct roff {
108 enum mparset parsetype; /* requested parse type */
109 struct mparse *parse; /* parse point */
110 struct roffnode *last; /* leaf of stack */
111 enum roffrule rstack[RSTACK_MAX]; /* stack of !`ie' rules */
112 char control; /* control character */
113 int rstackpos; /* position in rstack */
114 struct reg regs[REG__MAX];
115 struct roffkv *strtab; /* user-defined strings & macros */
116 struct roffkv *xmbtab; /* multi-byte trans table (`tr') */
117 struct roffstr *xtab; /* single-byte trans table (`tr') */
118 const char *current_string; /* value of last called user macro */
119 struct tbl_node *first_tbl; /* first table parsed */
120 struct tbl_node *last_tbl; /* last table parsed */
121 struct tbl_node *tbl; /* current table being parsed */
122 struct eqn_node *last_eqn; /* last equation parsed */
123 struct eqn_node *first_eqn; /* first equation parsed */
124 struct eqn_node *eqn; /* current equation being parsed */
125 };
126
127 struct roffnode {
128 enum rofft tok; /* type of node */
129 struct roffnode *parent; /* up one in stack */
130 int line; /* parse line */
131 int col; /* parse col */
132 char *name; /* node name, e.g. macro name */
133 char *end; /* end-rules: custom token */
134 int endspan; /* end-rules: next-line or infty */
135 enum roffrule rule; /* current evaluation rule */
136 };
137
138 #define ROFF_ARGS struct roff *r, /* parse ctx */ \
139 enum rofft tok, /* tok of macro */ \
140 char **bufp, /* input buffer */ \
141 size_t *szp, /* size of input buffer */ \
142 int ln, /* parse line */ \
143 int ppos, /* original pos in buffer */ \
144 int pos, /* current pos in buffer */ \
145 int *offs /* reset offset of buffer data */
146
147 typedef enum rofferr (*roffproc)(ROFF_ARGS);
148
149 struct roffmac {
150 const char *name; /* macro name */
151 roffproc proc; /* process new macro */
152 roffproc text; /* process as child text of macro */
153 roffproc sub; /* process as child of macro */
154 int flags;
155 #define ROFFMAC_STRUCT (1 << 0) /* always interpret */
156 struct roffmac *next;
157 };
158
159 struct predef {
160 const char *name; /* predefined input name */
161 const char *str; /* replacement symbol */
162 };
163
164 #define PREDEF(__name, __str) \
165 { (__name), (__str) },
166
167 static enum rofft roffhash_find(const char *, size_t);
168 static void roffhash_init(void);
169 static void roffnode_cleanscope(struct roff *);
170 static void roffnode_pop(struct roff *);
171 static void roffnode_push(struct roff *, enum rofft,
172 const char *, int, int);
173 static enum rofferr roff_block(ROFF_ARGS);
174 static enum rofferr roff_block_text(ROFF_ARGS);
175 static enum rofferr roff_block_sub(ROFF_ARGS);
176 static enum rofferr roff_cblock(ROFF_ARGS);
177 static enum rofferr roff_cc(ROFF_ARGS);
178 static enum rofferr roff_ccond(ROFF_ARGS);
179 static enum rofferr roff_cond(ROFF_ARGS);
180 static enum rofferr roff_cond_text(ROFF_ARGS);
181 static enum rofferr roff_cond_sub(ROFF_ARGS);
182 static enum rofferr roff_ds(ROFF_ARGS);
183 static enum roffrule roff_evalcond(const char *, int *);
184 static void roff_free1(struct roff *);
185 static void roff_freestr(struct roffkv *);
186 static char *roff_getname(struct roff *, char **, int, int);
187 static const char *roff_getstrn(const struct roff *,
188 const char *, size_t);
189 static enum rofferr roff_line_ignore(ROFF_ARGS);
190 static enum rofferr roff_nr(ROFF_ARGS);
191 static void roff_openeqn(struct roff *, const char *,
192 int, int, const char *);
193 static enum rofft roff_parse(struct roff *, const char *, int *);
194 static enum rofferr roff_parsetext(char *);
195 static enum rofferr roff_res(struct roff *,
196 char **, size_t *, int, int);
197 static enum rofferr roff_rm(ROFF_ARGS);
198 static void roff_setstr(struct roff *,
199 const char *, const char *, int);
200 static void roff_setstrn(struct roffkv **, const char *,
201 size_t, const char *, size_t, int);
202 static enum rofferr roff_so(ROFF_ARGS);
203 static enum rofferr roff_tr(ROFF_ARGS);
204 static enum rofferr roff_Dd(ROFF_ARGS);
205 static enum rofferr roff_TH(ROFF_ARGS);
206 static enum rofferr roff_TE(ROFF_ARGS);
207 static enum rofferr roff_TS(ROFF_ARGS);
208 static enum rofferr roff_EQ(ROFF_ARGS);
209 static enum rofferr roff_EN(ROFF_ARGS);
210 static enum rofferr roff_T_(ROFF_ARGS);
211 static enum rofferr roff_userdef(ROFF_ARGS);
212
213 /* See roffhash_find() */
214
215 #define ASCII_HI 126
216 #define ASCII_LO 33
217 #define HASHWIDTH (ASCII_HI - ASCII_LO + 1)
218
219 static struct roffmac *hash[HASHWIDTH];
220
221 static struct roffmac roffs[ROFF_MAX] = {
222 { "ad", roff_line_ignore, NULL, NULL, 0, NULL },
223 { "am", roff_block, roff_block_text, roff_block_sub, 0, NULL },
224 { "ami", roff_block, roff_block_text, roff_block_sub, 0, NULL },
225 { "am1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
226 { "cc", roff_cc, NULL, NULL, 0, NULL },
227 { "de", roff_block, roff_block_text, roff_block_sub, 0, NULL },
228 { "dei", roff_block, roff_block_text, roff_block_sub, 0, NULL },
229 { "de1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
230 { "ds", roff_ds, NULL, NULL, 0, NULL },
231 { "el", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
232 { "hy", roff_line_ignore, NULL, NULL, 0, NULL },
233 { "ie", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
234 { "if", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
235 { "ig", roff_block, roff_block_text, roff_block_sub, 0, NULL },
236 { "it", roff_line_ignore, NULL, NULL, 0, NULL },
237 { "ne", roff_line_ignore, NULL, NULL, 0, NULL },
238 { "nh", roff_line_ignore, NULL, NULL, 0, NULL },
239 { "nr", roff_nr, NULL, NULL, 0, NULL },
240 { "ns", roff_line_ignore, NULL, NULL, 0, NULL },
241 { "ps", roff_line_ignore, NULL, NULL, 0, NULL },
242 { "rm", roff_rm, NULL, NULL, 0, NULL },
243 { "so", roff_so, NULL, NULL, 0, NULL },
244 { "ta", roff_line_ignore, NULL, NULL, 0, NULL },
245 { "tr", roff_tr, NULL, NULL, 0, NULL },
246 { "Dd", roff_Dd, NULL, NULL, 0, NULL },
247 { "TH", roff_TH, NULL, NULL, 0, NULL },
248 { "TS", roff_TS, NULL, NULL, 0, NULL },
249 { "TE", roff_TE, NULL, NULL, 0, NULL },
250 { "T&", roff_T_, NULL, NULL, 0, NULL },
251 { "EQ", roff_EQ, NULL, NULL, 0, NULL },
252 { "EN", roff_EN, NULL, NULL, 0, NULL },
253 { ".", roff_cblock, NULL, NULL, 0, NULL },
254 { "\\}", roff_ccond, NULL, NULL, 0, NULL },
255 { NULL, roff_userdef, NULL, NULL, 0, NULL },
256 };
257
258 const char *const __mdoc_reserved[] = {
259 "Ac", "Ad", "An", "Ao", "Ap", "Aq", "Ar", "At",
260 "Bc", "Bd", "Bf", "Bk", "Bl", "Bo", "Bq",
261 "Brc", "Bro", "Brq", "Bsx", "Bt", "Bx",
262 "Cd", "Cm", "Db", "Dc", "Dd", "Dl", "Do", "Dq",
263 "Ds", "Dt", "Dv", "Dx", "D1",
264 "Ec", "Ed", "Ef", "Ek", "El", "Em", "em",
265 "En", "Eo", "Eq", "Er", "Es", "Ev", "Ex",
266 "Fa", "Fc", "Fd", "Fl", "Fn", "Fo", "Fr", "Ft", "Fx",
267 "Hf", "Ic", "In", "It", "Lb", "Li", "Lk", "Lp", "LP",
268 "Me", "Ms", "Mt", "Nd", "Nm", "No", "Ns", "Nx",
269 "Oc", "Oo", "Op", "Os", "Ot", "Ox",
270 "Pa", "Pc", "Pf", "Po", "Pp", "PP", "pp", "Pq",
271 "Qc", "Ql", "Qo", "Qq", "Or", "Rd", "Re", "Rs", "Rv",
272 "Sc", "Sf", "Sh", "SH", "Sm", "So", "Sq",
273 "Ss", "St", "Sx", "Sy",
274 "Ta", "Tn", "Ud", "Ux", "Va", "Vt", "Xc", "Xo", "Xr",
275 "%A", "%B", "%D", "%I", "%J", "%N", "%O",
276 "%P", "%Q", "%R", "%T", "%U", "%V",
277 NULL
278 };
279
280 const char *const __man_reserved[] = {
281 "AT", "B", "BI", "BR", "BT", "DE", "DS", "DT",
282 "EE", "EN", "EQ", "EX", "HF", "HP", "I", "IB", "IP", "IR",
283 "LP", "ME", "MT", "OP", "P", "PD", "PP", "PT",
284 "R", "RB", "RE", "RI", "RS", "SB", "SH", "SM", "SS", "SY",
285 "TE", "TH", "TP", "TQ", "TS", "T&", "UC", "UE", "UR", "YS",
286 NULL
287 };
288
289 /* Array of injected predefined strings. */
290 #define PREDEFS_MAX 38
291 static const struct predef predefs[PREDEFS_MAX] = {
292 #include "predefs.in"
293 };
294
295 /* See roffhash_find() */
296 #define ROFF_HASH(p) (p[0] - ASCII_LO)
297
298 static void
299 roffhash_init(void)
300 {
301 struct roffmac *n;
302 int buc, i;
303
304 for (i = 0; i < (int)ROFF_USERDEF; i++) {
305 assert(roffs[i].name[0] >= ASCII_LO);
306 assert(roffs[i].name[0] <= ASCII_HI);
307
308 buc = ROFF_HASH(roffs[i].name);
309
310 if (NULL != (n = hash[buc])) {
311 for ( ; n->next; n = n->next)
312 /* Do nothing. */ ;
313 n->next = &roffs[i];
314 } else
315 hash[buc] = &roffs[i];
316 }
317 }
318
319 /*
320 * Look up a roff token by its name. Returns ROFF_MAX if no macro by
321 * the nil-terminated string name could be found.
322 */
323 static enum rofft
324 roffhash_find(const char *p, size_t s)
325 {
326 int buc;
327 struct roffmac *n;
328
329 /*
330 * libroff has an extremely simple hashtable, for the time
331 * being, which simply keys on the first character, which must
332 * be printable, then walks a chain. It works well enough until
333 * optimised.
334 */
335
336 if (p[0] < ASCII_LO || p[0] > ASCII_HI)
337 return(ROFF_MAX);
338
339 buc = ROFF_HASH(p);
340
341 if (NULL == (n = hash[buc]))
342 return(ROFF_MAX);
343 for ( ; n; n = n->next)
344 if (0 == strncmp(n->name, p, s) && '\0' == n->name[(int)s])
345 return((enum rofft)(n - roffs));
346
347 return(ROFF_MAX);
348 }
349
350
351 /*
352 * Pop the current node off of the stack of roff instructions currently
353 * pending.
354 */
355 static void
356 roffnode_pop(struct roff *r)
357 {
358 struct roffnode *p;
359
360 assert(r->last);
361 p = r->last;
362
363 r->last = r->last->parent;
364 free(p->name);
365 free(p->end);
366 free(p);
367 }
368
369
370 /*
371 * Push a roff node onto the instruction stack. This must later be
372 * removed with roffnode_pop().
373 */
374 static void
375 roffnode_push(struct roff *r, enum rofft tok, const char *name,
376 int line, int col)
377 {
378 struct roffnode *p;
379
380 p = mandoc_calloc(1, sizeof(struct roffnode));
381 p->tok = tok;
382 if (name)
383 p->name = mandoc_strdup(name);
384 p->parent = r->last;
385 p->line = line;
386 p->col = col;
387 p->rule = p->parent ? p->parent->rule : ROFFRULE_DENY;
388
389 r->last = p;
390 }
391
392
393 static void
394 roff_free1(struct roff *r)
395 {
396 struct tbl_node *tbl;
397 struct eqn_node *e;
398 int i;
399
400 while (NULL != (tbl = r->first_tbl)) {
401 r->first_tbl = tbl->next;
402 tbl_free(tbl);
403 }
404
405 r->first_tbl = r->last_tbl = r->tbl = NULL;
406
407 while (NULL != (e = r->first_eqn)) {
408 r->first_eqn = e->next;
409 eqn_free(e);
410 }
411
412 r->first_eqn = r->last_eqn = r->eqn = NULL;
413
414 while (r->last)
415 roffnode_pop(r);
416
417 roff_freestr(r->strtab);
418 roff_freestr(r->xmbtab);
419
420 r->strtab = r->xmbtab = NULL;
421
422 if (r->xtab)
423 for (i = 0; i < 128; i++)
424 free(r->xtab[i].p);
425
426 free(r->xtab);
427 r->xtab = NULL;
428 }
429
430 void
431 roff_reset(struct roff *r)
432 {
433 int i;
434
435 roff_free1(r);
436
437 r->control = 0;
438 memset(&r->regs, 0, sizeof(struct reg) * REG__MAX);
439
440 for (i = 0; i < PREDEFS_MAX; i++)
441 roff_setstr(r, predefs[i].name, predefs[i].str, 0);
442 }
443
444
445 void
446 roff_free(struct roff *r)
447 {
448
449 roff_free1(r);
450 free(r);
451 }
452
453
454 struct roff *
455 roff_alloc(enum mparset type, struct mparse *parse)
456 {
457 struct roff *r;
458 int i;
459
460 r = mandoc_calloc(1, sizeof(struct roff));
461 r->parsetype = type;
462 r->parse = parse;
463 r->rstackpos = -1;
464
465 roffhash_init();
466
467 for (i = 0; i < PREDEFS_MAX; i++)
468 roff_setstr(r, predefs[i].name, predefs[i].str, 0);
469
470 return(r);
471 }
472
473 /*
474 * Pre-filter each and every line for reserved words (one beginning with
475 * `\*', e.g., `\*(ab'). These must be handled before the actual line
476 * is processed.
477 * This also checks the syntax of regular escapes.
478 */
479 static enum rofferr
480 roff_res(struct roff *r, char **bufp, size_t *szp, int ln, int pos)
481 {
482 enum mandoc_esc esc;
483 const char *stesc; /* start of an escape sequence ('\\') */
484 const char *stnam; /* start of the name, after "[(*" */
485 const char *cp; /* end of the name, e.g. before ']' */
486 const char *res; /* the string to be substituted */
487 int i, maxl, expand_count;
488 size_t nsz;
489 char *n;
490
491 expand_count = 0;
492
493 again:
494 cp = *bufp + pos;
495 while (NULL != (cp = strchr(cp, '\\'))) {
496 stesc = cp++;
497
498 /*
499 * The second character must be an asterisk.
500 * If it isn't, skip it anyway: It is escaped,
501 * so it can't start another escape sequence.
502 */
503
504 if ('\0' == *cp)
505 return(ROFF_CONT);
506
507 if ('*' != *cp) {
508 res = cp;
509 esc = mandoc_escape(&cp, NULL, NULL);
510 if (ESCAPE_ERROR != esc)
511 continue;
512 cp = res;
513 mandoc_msg
514 (MANDOCERR_BADESCAPE, r->parse,
515 ln, (int)(stesc - *bufp), NULL);
516 return(ROFF_CONT);
517 }
518
519 cp++;
520
521 /*
522 * The third character decides the length
523 * of the name of the string.
524 * Save a pointer to the name.
525 */
526
527 switch (*cp) {
528 case ('\0'):
529 return(ROFF_CONT);
530 case ('('):
531 cp++;
532 maxl = 2;
533 break;
534 case ('['):
535 cp++;
536 maxl = 0;
537 break;
538 default:
539 maxl = 1;
540 break;
541 }
542 stnam = cp;
543
544 /* Advance to the end of the name. */
545
546 for (i = 0; 0 == maxl || i < maxl; i++, cp++) {
547 if ('\0' == *cp) {
548 mandoc_msg
549 (MANDOCERR_BADESCAPE,
550 r->parse, ln,
551 (int)(stesc - *bufp), NULL);
552 return(ROFF_CONT);
553 }
554 if (0 == maxl && ']' == *cp)
555 break;
556 }
557
558 /*
559 * Retrieve the replacement string; if it is
560 * undefined, resume searching for escapes.
561 */
562
563 res = roff_getstrn(r, stnam, (size_t)i);
564
565 if (NULL == res) {
566 mandoc_msg
567 (MANDOCERR_BADESCAPE, r->parse,
568 ln, (int)(stesc - *bufp), NULL);
569 res = "";
570 }
571
572 /* Replace the escape sequence by the string. */
573
574 pos = stesc - *bufp;
575
576 nsz = *szp + strlen(res) + 1;
577 n = mandoc_malloc(nsz);
578
579 strlcpy(n, *bufp, (size_t)(stesc - *bufp + 1));
580 strlcat(n, res, nsz);
581 strlcat(n, cp + (maxl ? 0 : 1), nsz);
582
583 free(*bufp);
584
585 *bufp = n;
586 *szp = nsz;
587
588 if (EXPAND_LIMIT >= ++expand_count)
589 goto again;
590
591 /* Just leave the string unexpanded. */
592 mandoc_msg(MANDOCERR_ROFFLOOP, r->parse, ln, pos, NULL);
593 return(ROFF_IGN);
594 }
595 return(ROFF_CONT);
596 }
597
598 /*
599 * Process text streams: convert all breakable hyphens into ASCII_HYPH.
600 */
601 static enum rofferr
602 roff_parsetext(char *p)
603 {
604 size_t sz;
605 const char *start;
606 enum mandoc_esc esc;
607
608 start = p;
609
610 while ('\0' != *p) {
611 sz = strcspn(p, "-\\");
612 p += sz;
613
614 if ('\0' == *p)
615 break;
616
617 if ('\\' == *p) {
618 /* Skip over escapes. */
619 p++;
620 esc = mandoc_escape
621 ((const char **)&p, NULL, NULL);
622 if (ESCAPE_ERROR == esc)
623 break;
624 continue;
625 } else if (p == start) {
626 p++;
627 continue;
628 }
629
630 if (isalpha((unsigned char)p[-1]) &&
631 isalpha((unsigned char)p[1]))
632 *p = ASCII_HYPH;
633 p++;
634 }
635
636 return(ROFF_CONT);
637 }
638
639 enum rofferr
640 roff_parseln(struct roff *r, int ln, char **bufp,
641 size_t *szp, int pos, int *offs)
642 {
643 enum rofft t;
644 enum rofferr e;
645 int ppos, ctl;
646
647 /*
648 * Run the reserved-word filter only if we have some reserved
649 * words to fill in.
650 */
651
652 e = roff_res(r, bufp, szp, ln, pos);
653 if (ROFF_IGN == e)
654 return(e);
655 assert(ROFF_CONT == e);
656
657 ppos = pos;
658 ctl = roff_getcontrol(r, *bufp, &pos);
659
660 /*
661 * First, if a scope is open and we're not a macro, pass the
662 * text through the macro's filter. If a scope isn't open and
663 * we're not a macro, just let it through.
664 * Finally, if there's an equation scope open, divert it into it
665 * no matter our state.
666 */
667
668 if (r->last && ! ctl) {
669 t = r->last->tok;
670 assert(roffs[t].text);
671 e = (*roffs[t].text)
672 (r, t, bufp, szp, ln, pos, pos, offs);
673 assert(ROFF_IGN == e || ROFF_CONT == e);
674 if (ROFF_CONT != e)
675 return(e);
676 if (r->eqn)
677 return(eqn_read(&r->eqn, ln, *bufp, pos, offs));
678 if (r->tbl)
679 return(tbl_read(r->tbl, ln, *bufp, pos));
680 return(roff_parsetext(*bufp + pos));
681 } else if ( ! ctl) {
682 if (r->eqn)
683 return(eqn_read(&r->eqn, ln, *bufp, pos, offs));
684 if (r->tbl)
685 return(tbl_read(r->tbl, ln, *bufp, pos));
686 return(roff_parsetext(*bufp + pos));
687 } else if (r->eqn)
688 return(eqn_read(&r->eqn, ln, *bufp, ppos, offs));
689
690 /*
691 * If a scope is open, go to the child handler for that macro,
692 * as it may want to preprocess before doing anything with it.
693 * Don't do so if an equation is open.
694 */
695
696 if (r->last) {
697 t = r->last->tok;
698 assert(roffs[t].sub);
699 return((*roffs[t].sub)
700 (r, t, bufp, szp,
701 ln, ppos, pos, offs));
702 }
703
704 /*
705 * Lastly, as we've no scope open, try to look up and execute
706 * the new macro. If no macro is found, simply return and let
707 * the compilers handle it.
708 */
709
710 if (ROFF_MAX == (t = roff_parse(r, *bufp, &pos)))
711 return(ROFF_CONT);
712
713 assert(roffs[t].proc);
714 return((*roffs[t].proc)
715 (r, t, bufp, szp,
716 ln, ppos, pos, offs));
717 }
718
719
720 void
721 roff_endparse(struct roff *r)
722 {
723
724 if (r->last)
725 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
726 r->last->line, r->last->col, NULL);
727
728 if (r->eqn) {
729 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
730 r->eqn->eqn.ln, r->eqn->eqn.pos, NULL);
731 eqn_end(&r->eqn);
732 }
733
734 if (r->tbl) {
735 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
736 r->tbl->line, r->tbl->pos, NULL);
737 tbl_end(&r->tbl);
738 }
739 }
740
741 /*
742 * Parse a roff node's type from the input buffer. This must be in the
743 * form of ".foo xxx" in the usual way.
744 */
745 static enum rofft
746 roff_parse(struct roff *r, const char *buf, int *pos)
747 {
748 const char *mac;
749 size_t maclen;
750 enum rofft t;
751
752 if ('\0' == buf[*pos] || '"' == buf[*pos] ||
753 '\t' == buf[*pos] || ' ' == buf[*pos])
754 return(ROFF_MAX);
755
756 /*
757 * We stop the macro parse at an escape, tab, space, or nil.
758 * However, `\}' is also a valid macro, so make sure we don't
759 * clobber it by seeing the `\' as the end of token.
760 */
761
762 mac = buf + *pos;
763 maclen = strcspn(mac + 1, " \\\t\0") + 1;
764
765 t = (r->current_string = roff_getstrn(r, mac, maclen))
766 ? ROFF_USERDEF : roffhash_find(mac, maclen);
767
768 *pos += (int)maclen;
769
770 while (buf[*pos] && ' ' == buf[*pos])
771 (*pos)++;
772
773 return(t);
774 }
775
776 /* ARGSUSED */
777 static enum rofferr
778 roff_cblock(ROFF_ARGS)
779 {
780
781 /*
782 * A block-close `..' should only be invoked as a child of an
783 * ignore macro, otherwise raise a warning and just ignore it.
784 */
785
786 if (NULL == r->last) {
787 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
788 return(ROFF_IGN);
789 }
790
791 switch (r->last->tok) {
792 case (ROFF_am):
793 /* FALLTHROUGH */
794 case (ROFF_ami):
795 /* FALLTHROUGH */
796 case (ROFF_am1):
797 /* FALLTHROUGH */
798 case (ROFF_de):
799 /* ROFF_de1 is remapped to ROFF_de in roff_block(). */
800 /* FALLTHROUGH */
801 case (ROFF_dei):
802 /* FALLTHROUGH */
803 case (ROFF_ig):
804 break;
805 default:
806 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
807 return(ROFF_IGN);
808 }
809
810 if ((*bufp)[pos])
811 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
812
813 roffnode_pop(r);
814 roffnode_cleanscope(r);
815 return(ROFF_IGN);
816
817 }
818
819
820 static void
821 roffnode_cleanscope(struct roff *r)
822 {
823
824 while (r->last) {
825 if (--r->last->endspan != 0)
826 break;
827 roffnode_pop(r);
828 }
829 }
830
831
832 /* ARGSUSED */
833 static enum rofferr
834 roff_ccond(ROFF_ARGS)
835 {
836
837 if (NULL == r->last) {
838 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
839 return(ROFF_IGN);
840 }
841
842 switch (r->last->tok) {
843 case (ROFF_el):
844 /* FALLTHROUGH */
845 case (ROFF_ie):
846 /* FALLTHROUGH */
847 case (ROFF_if):
848 break;
849 default:
850 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
851 return(ROFF_IGN);
852 }
853
854 if (r->last->endspan > -1) {
855 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
856 return(ROFF_IGN);
857 }
858
859 if ((*bufp)[pos])
860 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
861
862 roffnode_pop(r);
863 roffnode_cleanscope(r);
864 return(ROFF_IGN);
865 }
866
867
868 /* ARGSUSED */
869 static enum rofferr
870 roff_block(ROFF_ARGS)
871 {
872 int sv;
873 size_t sz;
874 char *name;
875
876 name = NULL;
877
878 if (ROFF_ig != tok) {
879 if ('\0' == (*bufp)[pos]) {
880 mandoc_msg(MANDOCERR_NOARGS, r->parse, ln, ppos, NULL);
881 return(ROFF_IGN);
882 }
883
884 /*
885 * Re-write `de1', since we don't really care about
886 * groff's strange compatibility mode, into `de'.
887 */
888
889 if (ROFF_de1 == tok)
890 tok = ROFF_de;
891 if (ROFF_de == tok)
892 name = *bufp + pos;
893 else
894 mandoc_msg(MANDOCERR_REQUEST, r->parse, ln, ppos,
895 roffs[tok].name);
896
897 while ((*bufp)[pos] && ! isspace((unsigned char)(*bufp)[pos]))
898 pos++;
899
900 while (isspace((unsigned char)(*bufp)[pos]))
901 (*bufp)[pos++] = '\0';
902 }
903
904 roffnode_push(r, tok, name, ln, ppos);
905
906 /*
907 * At the beginning of a `de' macro, clear the existing string
908 * with the same name, if there is one. New content will be
909 * added from roff_block_text() in multiline mode.
910 */
911
912 if (ROFF_de == tok)
913 roff_setstr(r, name, "", 0);
914
915 if ('\0' == (*bufp)[pos])
916 return(ROFF_IGN);
917
918 /* If present, process the custom end-of-line marker. */
919
920 sv = pos;
921 while ((*bufp)[pos] && ! isspace((unsigned char)(*bufp)[pos]))
922 pos++;
923
924 /*
925 * Note: groff does NOT like escape characters in the input.
926 * Instead of detecting this, we're just going to let it fly and
927 * to hell with it.
928 */
929
930 assert(pos > sv);
931 sz = (size_t)(pos - sv);
932
933 if (1 == sz && '.' == (*bufp)[sv])
934 return(ROFF_IGN);
935
936 r->last->end = mandoc_malloc(sz + 1);
937
938 memcpy(r->last->end, *bufp + sv, sz);
939 r->last->end[(int)sz] = '\0';
940
941 if ((*bufp)[pos])
942 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
943
944 return(ROFF_IGN);
945 }
946
947
948 /* ARGSUSED */
949 static enum rofferr
950 roff_block_sub(ROFF_ARGS)
951 {
952 enum rofft t;
953 int i, j;
954
955 /*
956 * First check whether a custom macro exists at this level. If
957 * it does, then check against it. This is some of groff's
958 * stranger behaviours. If we encountered a custom end-scope
959 * tag and that tag also happens to be a "real" macro, then we
960 * need to try interpreting it again as a real macro. If it's
961 * not, then return ignore. Else continue.
962 */
963
964 if (r->last->end) {
965 for (i = pos, j = 0; r->last->end[j]; j++, i++)
966 if ((*bufp)[i] != r->last->end[j])
967 break;
968
969 if ('\0' == r->last->end[j] &&
970 ('\0' == (*bufp)[i] ||
971 ' ' == (*bufp)[i] ||
972 '\t' == (*bufp)[i])) {
973 roffnode_pop(r);
974 roffnode_cleanscope(r);
975
976 while (' ' == (*bufp)[i] || '\t' == (*bufp)[i])
977 i++;
978
979 pos = i;
980 if (ROFF_MAX != roff_parse(r, *bufp, &pos))
981 return(ROFF_RERUN);
982 return(ROFF_IGN);
983 }
984 }
985
986 /*
987 * If we have no custom end-query or lookup failed, then try
988 * pulling it out of the hashtable.
989 */
990
991 t = roff_parse(r, *bufp, &pos);
992
993 /*
994 * Macros other than block-end are only significant
995 * in `de' blocks; elsewhere, simply throw them away.
996 */
997 if (ROFF_cblock != t) {
998 if (ROFF_de == tok)
999 roff_setstr(r, r->last->name, *bufp + ppos, 1);
1000 return(ROFF_IGN);
1001 }
1002
1003 assert(roffs[t].proc);
1004 return((*roffs[t].proc)(r, t, bufp, szp,
1005 ln, ppos, pos, offs));
1006 }
1007
1008
1009 /* ARGSUSED */
1010 static enum rofferr
1011 roff_block_text(ROFF_ARGS)
1012 {
1013
1014 if (ROFF_de == tok)
1015 roff_setstr(r, r->last->name, *bufp + pos, 1);
1016
1017 return(ROFF_IGN);
1018 }
1019
1020
1021 /* ARGSUSED */
1022 static enum rofferr
1023 roff_cond_sub(ROFF_ARGS)
1024 {
1025 enum rofft t;
1026 enum roffrule rr;
1027 char *ep;
1028
1029 rr = r->last->rule;
1030 roffnode_cleanscope(r);
1031 t = roff_parse(r, *bufp, &pos);
1032
1033 /*
1034 * Fully handle known macros when they are structurally
1035 * required or when the conditional evaluated to true.
1036 */
1037
1038 if ((ROFF_MAX != t) &&
1039 (ROFF_ccond == t || ROFFRULE_ALLOW == rr ||
1040 ROFFMAC_STRUCT & roffs[t].flags)) {
1041 assert(roffs[t].proc);
1042 return((*roffs[t].proc)(r, t, bufp, szp,
1043 ln, ppos, pos, offs));
1044 }
1045
1046 /* Always check for the closing delimiter `\}'. */
1047
1048 ep = &(*bufp)[pos];
1049 while (NULL != (ep = strchr(ep, '\\'))) {
1050 if ('}' != *(++ep))
1051 continue;
1052
1053 /*
1054 * If we're at the end of line, then just chop
1055 * off the \} and resize the buffer.
1056 * If we aren't, then convert it to spaces.
1057 */
1058
1059 if ('\0' == *(ep + 1)) {
1060 *--ep = '\0';
1061 *szp -= 2;
1062 } else
1063 *(ep - 1) = *ep = ' ';
1064
1065 roff_ccond(r, ROFF_ccond, bufp, szp,
1066 ln, pos, pos + 2, offs);
1067 break;
1068 }
1069 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
1070 }
1071
1072 /* ARGSUSED */
1073 static enum rofferr
1074 roff_cond_text(ROFF_ARGS)
1075 {
1076 char *ep;
1077 enum roffrule rr;
1078
1079 rr = r->last->rule;
1080 roffnode_cleanscope(r);
1081
1082 ep = &(*bufp)[pos];
1083 for ( ; NULL != (ep = strchr(ep, '\\')); ep++) {
1084 ep++;
1085 if ('}' != *ep)
1086 continue;
1087 *ep = '&';
1088 roff_ccond(r, ROFF_ccond, bufp, szp,
1089 ln, pos, pos + 2, offs);
1090 }
1091 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
1092 }
1093
1094 static enum roffrule
1095 roff_evalcond(const char *v, int *pos)
1096 {
1097
1098 switch (v[*pos]) {
1099 case ('n'):
1100 (*pos)++;
1101 return(ROFFRULE_ALLOW);
1102 case ('e'):
1103 /* FALLTHROUGH */
1104 case ('o'):
1105 /* FALLTHROUGH */
1106 case ('t'):
1107 (*pos)++;
1108 return(ROFFRULE_DENY);
1109 default:
1110 break;
1111 }
1112
1113 while (v[*pos] && ' ' != v[*pos])
1114 (*pos)++;
1115 return(ROFFRULE_DENY);
1116 }
1117
1118 /* ARGSUSED */
1119 static enum rofferr
1120 roff_line_ignore(ROFF_ARGS)
1121 {
1122
1123 if (ROFF_it == tok)
1124 mandoc_msg(MANDOCERR_REQUEST, r->parse, ln, ppos, "it");
1125
1126 return(ROFF_IGN);
1127 }
1128
1129 /* ARGSUSED */
1130 static enum rofferr
1131 roff_cond(ROFF_ARGS)
1132 {
1133
1134 roffnode_push(r, tok, NULL, ln, ppos);
1135
1136 /*
1137 * An `.el' has no conditional body: it will consume the value
1138 * of the current rstack entry set in prior `ie' calls or
1139 * defaults to DENY.
1140 *
1141 * If we're not an `el', however, then evaluate the conditional.
1142 */
1143
1144 r->last->rule = ROFF_el == tok ?
1145 (r->rstackpos < 0 ?
1146 ROFFRULE_DENY : r->rstack[r->rstackpos--]) :
1147 roff_evalcond(*bufp, &pos);
1148
1149 /*
1150 * An if-else will put the NEGATION of the current evaluated
1151 * conditional into the stack of rules.
1152 */
1153
1154 if (ROFF_ie == tok) {
1155 if (r->rstackpos == RSTACK_MAX - 1) {
1156 mandoc_msg(MANDOCERR_MEM,
1157 r->parse, ln, ppos, NULL);
1158 return(ROFF_ERR);
1159 }
1160 r->rstack[++r->rstackpos] =
1161 ROFFRULE_DENY == r->last->rule ?
1162 ROFFRULE_ALLOW : ROFFRULE_DENY;
1163 }
1164
1165 /* If the parent has false as its rule, then so do we. */
1166
1167 if (r->last->parent && ROFFRULE_DENY == r->last->parent->rule)
1168 r->last->rule = ROFFRULE_DENY;
1169
1170 /*
1171 * Determine scope.
1172 * If there is nothing on the line after the conditional,
1173 * not even whitespace, use next-line scope.
1174 */
1175
1176 if ('\0' == (*bufp)[pos]) {
1177 r->last->endspan = 2;
1178 goto out;
1179 }
1180
1181 while (' ' == (*bufp)[pos])
1182 pos++;
1183
1184 /* An opening brace requests multiline scope. */
1185
1186 if ('\\' == (*bufp)[pos] && '{' == (*bufp)[pos + 1]) {
1187 r->last->endspan = -1;
1188 pos += 2;
1189 goto out;
1190 }
1191
1192 /*
1193 * Anything else following the conditional causes
1194 * single-line scope. Warn if the scope contains
1195 * nothing but trailing whitespace.
1196 */
1197
1198 if ('\0' == (*bufp)[pos])
1199 mandoc_msg(MANDOCERR_NOARGS, r->parse, ln, ppos, NULL);
1200
1201 r->last->endspan = 1;
1202
1203 out:
1204 *offs = pos;
1205 return(ROFF_RERUN);
1206 }
1207
1208
1209 /* ARGSUSED */
1210 static enum rofferr
1211 roff_ds(ROFF_ARGS)
1212 {
1213 char *name, *string;
1214
1215 /*
1216 * A symbol is named by the first word following the macro
1217 * invocation up to a space. Its value is anything after the
1218 * name's trailing whitespace and optional double-quote. Thus,
1219 *
1220 * [.ds foo "bar " ]
1221 *
1222 * will have `bar " ' as its value.
1223 */
1224
1225 string = *bufp + pos;
1226 name = roff_getname(r, &string, ln, pos);
1227 if ('\0' == *name)
1228 return(ROFF_IGN);
1229
1230 /* Read past initial double-quote. */
1231 if ('"' == *string)
1232 string++;
1233
1234 /* The rest is the value. */
1235 roff_setstr(r, name, string, 0);
1236 return(ROFF_IGN);
1237 }
1238
1239 int
1240 roff_regisset(const struct roff *r, enum regs reg)
1241 {
1242
1243 return(r->regs[(int)reg].set);
1244 }
1245
1246 unsigned int
1247 roff_regget(const struct roff *r, enum regs reg)
1248 {
1249
1250 return(r->regs[(int)reg].u);
1251 }
1252
1253 void
1254 roff_regunset(struct roff *r, enum regs reg)
1255 {
1256
1257 r->regs[(int)reg].set = 0;
1258 }
1259
1260 /* ARGSUSED */
1261 static enum rofferr
1262 roff_nr(ROFF_ARGS)
1263 {
1264 const char *key;
1265 char *val;
1266 int iv;
1267
1268 val = *bufp + pos;
1269 key = roff_getname(r, &val, ln, pos);
1270
1271 if (0 == strcmp(key, "nS")) {
1272 r->regs[(int)REG_nS].set = 1;
1273 if ((iv = mandoc_strntoi(val, strlen(val), 10)) >= 0)
1274 r->regs[(int)REG_nS].u = (unsigned)iv;
1275 else
1276 r->regs[(int)REG_nS].u = 0u;
1277 }
1278
1279 return(ROFF_IGN);
1280 }
1281
1282 /* ARGSUSED */
1283 static enum rofferr
1284 roff_rm(ROFF_ARGS)
1285 {
1286 const char *name;
1287 char *cp;
1288
1289 cp = *bufp + pos;
1290 while ('\0' != *cp) {
1291 name = roff_getname(r, &cp, ln, (int)(cp - *bufp));
1292 if ('\0' != *name)
1293 roff_setstr(r, name, NULL, 0);
1294 }
1295 return(ROFF_IGN);
1296 }
1297
1298 /* ARGSUSED */
1299 static enum rofferr
1300 roff_Dd(ROFF_ARGS)
1301 {
1302 const char *const *cp;
1303
1304 if (MPARSE_MDOC != r->parsetype)
1305 for (cp = __mdoc_reserved; *cp; cp++)
1306 roff_setstr(r, *cp, NULL, 0);
1307
1308 return(ROFF_CONT);
1309 }
1310
1311 /* ARGSUSED */
1312 static enum rofferr
1313 roff_TH(ROFF_ARGS)
1314 {
1315 const char *const *cp;
1316
1317 if (MPARSE_MDOC != r->parsetype)
1318 for (cp = __man_reserved; *cp; cp++)
1319 roff_setstr(r, *cp, NULL, 0);
1320
1321 return(ROFF_CONT);
1322 }
1323
1324 /* ARGSUSED */
1325 static enum rofferr
1326 roff_TE(ROFF_ARGS)
1327 {
1328
1329 if (NULL == r->tbl)
1330 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1331 else
1332 tbl_end(&r->tbl);
1333
1334 return(ROFF_IGN);
1335 }
1336
1337 /* ARGSUSED */
1338 static enum rofferr
1339 roff_T_(ROFF_ARGS)
1340 {
1341
1342 if (NULL == r->tbl)
1343 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1344 else
1345 tbl_restart(ppos, ln, r->tbl);
1346
1347 return(ROFF_IGN);
1348 }
1349
1350 #if 0
1351 static int
1352 roff_closeeqn(struct roff *r)
1353 {
1354
1355 return(r->eqn && ROFF_EQN == eqn_end(&r->eqn) ? 1 : 0);
1356 }
1357 #endif
1358
1359 static void
1360 roff_openeqn(struct roff *r, const char *name, int line,
1361 int offs, const char *buf)
1362 {
1363 struct eqn_node *e;
1364 int poff;
1365
1366 assert(NULL == r->eqn);
1367 e = eqn_alloc(name, offs, line, r->parse);
1368
1369 if (r->last_eqn)
1370 r->last_eqn->next = e;
1371 else
1372 r->first_eqn = r->last_eqn = e;
1373
1374 r->eqn = r->last_eqn = e;
1375
1376 if (buf) {
1377 poff = 0;
1378 eqn_read(&r->eqn, line, buf, offs, &poff);
1379 }
1380 }
1381
1382 /* ARGSUSED */
1383 static enum rofferr
1384 roff_EQ(ROFF_ARGS)
1385 {
1386
1387 roff_openeqn(r, *bufp + pos, ln, ppos, NULL);
1388 return(ROFF_IGN);
1389 }
1390
1391 /* ARGSUSED */
1392 static enum rofferr
1393 roff_EN(ROFF_ARGS)
1394 {
1395
1396 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1397 return(ROFF_IGN);
1398 }
1399
1400 /* ARGSUSED */
1401 static enum rofferr
1402 roff_TS(ROFF_ARGS)
1403 {
1404 struct tbl_node *tbl;
1405
1406 if (r->tbl) {
1407 mandoc_msg(MANDOCERR_SCOPEBROKEN, r->parse, ln, ppos, NULL);
1408 tbl_end(&r->tbl);
1409 }
1410
1411 tbl = tbl_alloc(ppos, ln, r->parse);
1412
1413 if (r->last_tbl)
1414 r->last_tbl->next = tbl;
1415 else
1416 r->first_tbl = r->last_tbl = tbl;
1417
1418 r->tbl = r->last_tbl = tbl;
1419 return(ROFF_IGN);
1420 }
1421
1422 /* ARGSUSED */
1423 static enum rofferr
1424 roff_cc(ROFF_ARGS)
1425 {
1426 const char *p;
1427
1428 p = *bufp + pos;
1429
1430 if ('\0' == *p || '.' == (r->control = *p++))
1431 r->control = 0;
1432
1433 if ('\0' != *p)
1434 mandoc_msg(MANDOCERR_ARGCOUNT, r->parse, ln, ppos, NULL);
1435
1436 return(ROFF_IGN);
1437 }
1438
1439 /* ARGSUSED */
1440 static enum rofferr
1441 roff_tr(ROFF_ARGS)
1442 {
1443 const char *p, *first, *second;
1444 size_t fsz, ssz;
1445 enum mandoc_esc esc;
1446
1447 p = *bufp + pos;
1448
1449 if ('\0' == *p) {
1450 mandoc_msg(MANDOCERR_ARGCOUNT, r->parse, ln, ppos, NULL);
1451 return(ROFF_IGN);
1452 }
1453
1454 while ('\0' != *p) {
1455 fsz = ssz = 1;
1456
1457 first = p++;
1458 if ('\\' == *first) {
1459 esc = mandoc_escape(&p, NULL, NULL);
1460 if (ESCAPE_ERROR == esc) {
1461 mandoc_msg
1462 (MANDOCERR_BADESCAPE, r->parse,
1463 ln, (int)(p - *bufp), NULL);
1464 return(ROFF_IGN);
1465 }
1466 fsz = (size_t)(p - first);
1467 }
1468
1469 second = p++;
1470 if ('\\' == *second) {
1471 esc = mandoc_escape(&p, NULL, NULL);
1472 if (ESCAPE_ERROR == esc) {
1473 mandoc_msg
1474 (MANDOCERR_BADESCAPE, r->parse,
1475 ln, (int)(p - *bufp), NULL);
1476 return(ROFF_IGN);
1477 }
1478 ssz = (size_t)(p - second);
1479 } else if ('\0' == *second) {
1480 mandoc_msg(MANDOCERR_ARGCOUNT, r->parse,
1481 ln, (int)(p - *bufp), NULL);
1482 second = " ";
1483 p--;
1484 }
1485
1486 if (fsz > 1) {
1487 roff_setstrn(&r->xmbtab, first,
1488 fsz, second, ssz, 0);
1489 continue;
1490 }
1491
1492 if (NULL == r->xtab)
1493 r->xtab = mandoc_calloc
1494 (128, sizeof(struct roffstr));
1495
1496 free(r->xtab[(int)*first].p);
1497 r->xtab[(int)*first].p = mandoc_strndup(second, ssz);
1498 r->xtab[(int)*first].sz = ssz;
1499 }
1500
1501 return(ROFF_IGN);
1502 }
1503
1504 /* ARGSUSED */
1505 static enum rofferr
1506 roff_so(ROFF_ARGS)
1507 {
1508 char *name;
1509
1510 mandoc_msg(MANDOCERR_SO, r->parse, ln, ppos, NULL);
1511
1512 /*
1513 * Handle `so'. Be EXTREMELY careful, as we shouldn't be
1514 * opening anything that's not in our cwd or anything beneath
1515 * it. Thus, explicitly disallow traversing up the file-system
1516 * or using absolute paths.
1517 */
1518
1519 name = *bufp + pos;
1520 if ('/' == *name || strstr(name, "../") || strstr(name, "/..")) {
1521 mandoc_msg(MANDOCERR_SOPATH, r->parse, ln, pos, NULL);
1522 return(ROFF_ERR);
1523 }
1524
1525 *offs = pos;
1526 return(ROFF_SO);
1527 }
1528
1529 /* ARGSUSED */
1530 static enum rofferr
1531 roff_userdef(ROFF_ARGS)
1532 {
1533 const char *arg[9];
1534 char *cp, *n1, *n2;
1535 int i;
1536
1537 /*
1538 * Collect pointers to macro argument strings
1539 * and null-terminate them.
1540 */
1541 cp = *bufp + pos;
1542 for (i = 0; i < 9; i++)
1543 arg[i] = '\0' == *cp ? "" :
1544 mandoc_getarg(r->parse, &cp, ln, &pos);
1545
1546 /*
1547 * Expand macro arguments.
1548 */
1549 *szp = 0;
1550 n1 = cp = mandoc_strdup(r->current_string);
1551 while (NULL != (cp = strstr(cp, "\\$"))) {
1552 i = cp[2] - '1';
1553 if (0 > i || 8 < i) {
1554 /* Not an argument invocation. */
1555 cp += 2;
1556 continue;
1557 }
1558
1559 *szp = strlen(n1) - 3 + strlen(arg[i]) + 1;
1560 n2 = mandoc_malloc(*szp);
1561
1562 strlcpy(n2, n1, (size_t)(cp - n1 + 1));
1563 strlcat(n2, arg[i], *szp);
1564 strlcat(n2, cp + 3, *szp);
1565
1566 cp = n2 + (cp - n1);
1567 free(n1);
1568 n1 = n2;
1569 }
1570
1571 /*
1572 * Replace the macro invocation
1573 * by the expanded macro.
1574 */
1575 free(*bufp);
1576 *bufp = n1;
1577 if (0 == *szp)
1578 *szp = strlen(*bufp) + 1;
1579
1580 return(*szp > 1 && '\n' == (*bufp)[(int)*szp - 2] ?
1581 ROFF_REPARSE : ROFF_APPEND);
1582 }
1583
1584 static char *
1585 roff_getname(struct roff *r, char **cpp, int ln, int pos)
1586 {
1587 char *name, *cp;
1588
1589 name = *cpp;
1590 if ('\0' == *name)
1591 return(name);
1592
1593 /* Read until end of name. */
1594 for (cp = name; '\0' != *cp && ' ' != *cp; cp++) {
1595 if ('\\' != *cp)
1596 continue;
1597 cp++;
1598 if ('\\' == *cp)
1599 continue;
1600 mandoc_msg(MANDOCERR_NAMESC, r->parse, ln, pos, NULL);
1601 *cp = '\0';
1602 name = cp;
1603 }
1604
1605 /* Nil-terminate name. */
1606 if ('\0' != *cp)
1607 *(cp++) = '\0';
1608
1609 /* Read past spaces. */
1610 while (' ' == *cp)
1611 cp++;
1612
1613 *cpp = cp;
1614 return(name);
1615 }
1616
1617 /*
1618 * Store *string into the user-defined string called *name.
1619 * In multiline mode, append to an existing entry and append '\n';
1620 * else replace the existing entry, if there is one.
1621 * To clear an existing entry, call with (*r, *name, NULL, 0).
1622 */
1623 static void
1624 roff_setstr(struct roff *r, const char *name, const char *string,
1625 int multiline)
1626 {
1627
1628 roff_setstrn(&r->strtab, name, strlen(name), string,
1629 string ? strlen(string) : 0, multiline);
1630 }
1631
1632 static void
1633 roff_setstrn(struct roffkv **r, const char *name, size_t namesz,
1634 const char *string, size_t stringsz, int multiline)
1635 {
1636 struct roffkv *n;
1637 char *c;
1638 int i;
1639 size_t oldch, newch;
1640
1641 /* Search for an existing string with the same name. */
1642 n = *r;
1643
1644 while (n && strcmp(name, n->key.p))
1645 n = n->next;
1646
1647 if (NULL == n) {
1648 /* Create a new string table entry. */
1649 n = mandoc_malloc(sizeof(struct roffkv));
1650 n->key.p = mandoc_strndup(name, namesz);
1651 n->key.sz = namesz;
1652 n->val.p = NULL;
1653 n->val.sz = 0;
1654 n->next = *r;
1655 *r = n;
1656 } else if (0 == multiline) {
1657 /* In multiline mode, append; else replace. */
1658 free(n->val.p);
1659 n->val.p = NULL;
1660 n->val.sz = 0;
1661 }
1662
1663 if (NULL == string)
1664 return;
1665
1666 /*
1667 * One additional byte for the '\n' in multiline mode,
1668 * and one for the terminating '\0'.
1669 */
1670 newch = stringsz + (multiline ? 2u : 1u);
1671
1672 if (NULL == n->val.p) {
1673 n->val.p = mandoc_malloc(newch);
1674 *n->val.p = '\0';
1675 oldch = 0;
1676 } else {
1677 oldch = n->val.sz;
1678 n->val.p = mandoc_realloc(n->val.p, oldch + newch);
1679 }
1680
1681 /* Skip existing content in the destination buffer. */
1682 c = n->val.p + (int)oldch;
1683
1684 /* Append new content to the destination buffer. */
1685 i = 0;
1686 while (i < (int)stringsz) {
1687 /*
1688 * Rudimentary roff copy mode:
1689 * Handle escaped backslashes.
1690 */
1691 if ('\\' == string[i] && '\\' == string[i + 1])
1692 i++;
1693 *c++ = string[i++];
1694 }
1695
1696 /* Append terminating bytes. */
1697 if (multiline)
1698 *c++ = '\n';
1699
1700 *c = '\0';
1701 n->val.sz = (int)(c - n->val.p);
1702 }
1703
1704 static const char *
1705 roff_getstrn(const struct roff *r, const char *name, size_t len)
1706 {
1707 const struct roffkv *n;
1708
1709 for (n = r->strtab; n; n = n->next)
1710 if (0 == strncmp(name, n->key.p, len) &&
1711 '\0' == n->key.p[(int)len])
1712 return(n->val.p);
1713
1714 return(NULL);
1715 }
1716
1717 static void
1718 roff_freestr(struct roffkv *r)
1719 {
1720 struct roffkv *n, *nn;
1721
1722 for (n = r; n; n = nn) {
1723 free(n->key.p);
1724 free(n->val.p);
1725 nn = n->next;
1726 free(n);
1727 }
1728 }
1729
1730 const struct tbl_span *
1731 roff_span(const struct roff *r)
1732 {
1733
1734 return(r->tbl ? tbl_span(r->tbl) : NULL);
1735 }
1736
1737 const struct eqn *
1738 roff_eqn(const struct roff *r)
1739 {
1740
1741 return(r->last_eqn ? &r->last_eqn->eqn : NULL);
1742 }
1743
1744 /*
1745 * Duplicate an input string, making the appropriate character
1746 * conversations (as stipulated by `tr') along the way.
1747 * Returns a heap-allocated string with all the replacements made.
1748 */
1749 char *
1750 roff_strdup(const struct roff *r, const char *p)
1751 {
1752 const struct roffkv *cp;
1753 char *res;
1754 const char *pp;
1755 size_t ssz, sz;
1756 enum mandoc_esc esc;
1757
1758 if (NULL == r->xmbtab && NULL == r->xtab)
1759 return(mandoc_strdup(p));
1760 else if ('\0' == *p)
1761 return(mandoc_strdup(""));
1762
1763 /*
1764 * Step through each character looking for term matches
1765 * (remember that a `tr' can be invoked with an escape, which is
1766 * a glyph but the escape is multi-character).
1767 * We only do this if the character hash has been initialised
1768 * and the string is >0 length.
1769 */
1770
1771 res = NULL;
1772 ssz = 0;
1773
1774 while ('\0' != *p) {
1775 if ('\\' != *p && r->xtab && r->xtab[(int)*p].p) {
1776 sz = r->xtab[(int)*p].sz;
1777 res = mandoc_realloc(res, ssz + sz + 1);
1778 memcpy(res + ssz, r->xtab[(int)*p].p, sz);
1779 ssz += sz;
1780 p++;
1781 continue;
1782 } else if ('\\' != *p) {
1783 res = mandoc_realloc(res, ssz + 2);
1784 res[ssz++] = *p++;
1785 continue;
1786 }
1787
1788 /* Search for term matches. */
1789 for (cp = r->xmbtab; cp; cp = cp->next)
1790 if (0 == strncmp(p, cp->key.p, cp->key.sz))
1791 break;
1792
1793 if (NULL != cp) {
1794 /*
1795 * A match has been found.
1796 * Append the match to the array and move
1797 * forward by its keysize.
1798 */
1799 res = mandoc_realloc
1800 (res, ssz + cp->val.sz + 1);
1801 memcpy(res + ssz, cp->val.p, cp->val.sz);
1802 ssz += cp->val.sz;
1803 p += (int)cp->key.sz;
1804 continue;
1805 }
1806
1807 /*
1808 * Handle escapes carefully: we need to copy
1809 * over just the escape itself, or else we might
1810 * do replacements within the escape itself.
1811 * Make sure to pass along the bogus string.
1812 */
1813 pp = p++;
1814 esc = mandoc_escape(&p, NULL, NULL);
1815 if (ESCAPE_ERROR == esc) {
1816 sz = strlen(pp);
1817 res = mandoc_realloc(res, ssz + sz + 1);
1818 memcpy(res + ssz, pp, sz);
1819 break;
1820 }
1821 /*
1822 * We bail out on bad escapes.
1823 * No need to warn: we already did so when
1824 * roff_res() was called.
1825 */
1826 sz = (int)(p - pp);
1827 res = mandoc_realloc(res, ssz + sz + 1);
1828 memcpy(res + ssz, pp, sz);
1829 ssz += sz;
1830 }
1831
1832 res[(int)ssz] = '\0';
1833 return(res);
1834 }
1835
1836 /*
1837 * Find out whether a line is a macro line or not.
1838 * If it is, adjust the current position and return one; if it isn't,
1839 * return zero and don't change the current position.
1840 * If the control character has been set with `.cc', then let that grain
1841 * precedence.
1842 * This is slighly contrary to groff, where using the non-breaking
1843 * control character when `cc' has been invoked will cause the
1844 * non-breaking macro contents to be printed verbatim.
1845 */
1846 int
1847 roff_getcontrol(const struct roff *r, const char *cp, int *ppos)
1848 {
1849 int pos;
1850
1851 pos = *ppos;
1852
1853 if (0 != r->control && cp[pos] == r->control)
1854 pos++;
1855 else if (0 != r->control)
1856 return(0);
1857 else if ('\\' == cp[pos] && '.' == cp[pos + 1])
1858 pos += 2;
1859 else if ('.' == cp[pos] || '\'' == cp[pos])
1860 pos++;
1861 else
1862 return(0);
1863
1864 while (' ' == cp[pos] || '\t' == cp[pos])
1865 pos++;
1866
1867 *ppos = pos;
1868 return(1);
1869 }