]> git.cameronkatri.com Git - mandoc.git/blob - roff.c
Remember to NULL-ify new keys/vals.
[mandoc.git] / roff.c
1 /* $Id: roff.c,v 1.146 2011/07/17 12:13:37 kristaps Exp $ */
2 /*
3 * Copyright (c) 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2010, 2011 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 enum rofft {
35 ROFF_ad,
36 ROFF_am,
37 ROFF_ami,
38 ROFF_am1,
39 ROFF_de,
40 ROFF_dei,
41 ROFF_de1,
42 ROFF_ds,
43 ROFF_el,
44 ROFF_hy,
45 ROFF_ie,
46 ROFF_if,
47 ROFF_ig,
48 ROFF_it,
49 ROFF_ne,
50 ROFF_nh,
51 ROFF_nr,
52 ROFF_ns,
53 ROFF_ps,
54 ROFF_rm,
55 ROFF_so,
56 ROFF_ta,
57 ROFF_tr,
58 ROFF_TS,
59 ROFF_TE,
60 ROFF_T_,
61 ROFF_EQ,
62 ROFF_EN,
63 ROFF_cblock,
64 ROFF_ccond,
65 ROFF_USERDEF,
66 ROFF_MAX
67 };
68
69 enum roffrule {
70 ROFFRULE_ALLOW,
71 ROFFRULE_DENY
72 };
73
74 struct roffstr {
75 char *name; /* key of symbol */
76 char *string; /* current value */
77 struct roffstr *next; /* next in list */
78 };
79
80 struct roff {
81 struct mparse *parse; /* parse point */
82 struct roffnode *last; /* leaf of stack */
83 enum roffrule rstack[RSTACK_MAX]; /* stack of !`ie' rules */
84 int rstackpos; /* position in rstack */
85 struct regset *regs; /* read/writable registers */
86 struct roffstr *first_string; /* user-defined strings & macros */
87 const char *current_string; /* value of last called user macro */
88 struct tbl_node *first_tbl; /* first table parsed */
89 struct tbl_node *last_tbl; /* last table parsed */
90 struct tbl_node *tbl; /* current table being parsed */
91 struct eqn_node *last_eqn; /* last equation parsed */
92 struct eqn_node *first_eqn; /* first equation parsed */
93 struct eqn_node *eqn; /* current equation being parsed */
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 struct predef {
129 const char *name; /* predefined input name */
130 const char *str; /* replacement symbol */
131 };
132
133 #define PREDEF(__name, __str) \
134 { (__name), (__str) },
135
136 static enum rofferr roff_block(ROFF_ARGS);
137 static enum rofferr roff_block_text(ROFF_ARGS);
138 static enum rofferr roff_block_sub(ROFF_ARGS);
139 static enum rofferr roff_cblock(ROFF_ARGS);
140 static enum rofferr roff_ccond(ROFF_ARGS);
141 static enum rofferr roff_cond(ROFF_ARGS);
142 static enum rofferr roff_cond_text(ROFF_ARGS);
143 static enum rofferr roff_cond_sub(ROFF_ARGS);
144 static enum rofferr roff_ds(ROFF_ARGS);
145 static enum roffrule roff_evalcond(const char *, int *);
146 static void roff_freestr(struct roff *);
147 static char *roff_getname(struct roff *, char **, int, int);
148 static const char *roff_getstrn(const struct roff *,
149 const char *, size_t);
150 static enum rofferr roff_line_ignore(ROFF_ARGS);
151 static enum rofferr roff_nr(ROFF_ARGS);
152 static int roff_res(struct roff *,
153 char **, size_t *, int, int);
154 static enum rofferr roff_rm(ROFF_ARGS);
155 static void roff_setstr(struct roff *,
156 const char *, const char *, int);
157 static enum rofferr roff_so(ROFF_ARGS);
158 static enum rofferr roff_TE(ROFF_ARGS);
159 static enum rofferr roff_TS(ROFF_ARGS);
160 static enum rofferr roff_EQ(ROFF_ARGS);
161 static enum rofferr roff_EN(ROFF_ARGS);
162 static enum rofferr roff_T_(ROFF_ARGS);
163 static enum rofferr roff_userdef(ROFF_ARGS);
164
165 /* See roff_hash_find() */
166
167 #define ASCII_HI 126
168 #define ASCII_LO 33
169 #define HASHWIDTH (ASCII_HI - ASCII_LO + 1)
170
171 static struct roffmac *hash[HASHWIDTH];
172
173 static struct roffmac roffs[ROFF_MAX] = {
174 { "ad", roff_line_ignore, NULL, NULL, 0, NULL },
175 { "am", roff_block, roff_block_text, roff_block_sub, 0, NULL },
176 { "ami", roff_block, roff_block_text, roff_block_sub, 0, NULL },
177 { "am1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
178 { "de", roff_block, roff_block_text, roff_block_sub, 0, NULL },
179 { "dei", roff_block, roff_block_text, roff_block_sub, 0, NULL },
180 { "de1", roff_block, roff_block_text, roff_block_sub, 0, NULL },
181 { "ds", roff_ds, NULL, NULL, 0, NULL },
182 { "el", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
183 { "hy", roff_line_ignore, NULL, NULL, 0, NULL },
184 { "ie", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
185 { "if", roff_cond, roff_cond_text, roff_cond_sub, ROFFMAC_STRUCT, NULL },
186 { "ig", roff_block, roff_block_text, roff_block_sub, 0, NULL },
187 { "it", roff_line_ignore, NULL, NULL, 0, NULL },
188 { "ne", roff_line_ignore, NULL, NULL, 0, NULL },
189 { "nh", roff_line_ignore, NULL, NULL, 0, NULL },
190 { "nr", roff_nr, NULL, NULL, 0, NULL },
191 { "ns", roff_line_ignore, NULL, NULL, 0, NULL },
192 { "ps", roff_line_ignore, NULL, NULL, 0, NULL },
193 { "rm", roff_rm, NULL, NULL, 0, NULL },
194 { "so", roff_so, NULL, NULL, 0, NULL },
195 { "ta", roff_line_ignore, NULL, NULL, 0, NULL },
196 { "tr", roff_line_ignore, NULL, NULL, 0, NULL },
197 { "TS", roff_TS, NULL, NULL, 0, NULL },
198 { "TE", roff_TE, NULL, NULL, 0, NULL },
199 { "T&", roff_T_, NULL, NULL, 0, NULL },
200 { "EQ", roff_EQ, NULL, NULL, 0, NULL },
201 { "EN", roff_EN, NULL, NULL, 0, NULL },
202 { ".", roff_cblock, NULL, NULL, 0, NULL },
203 { "\\}", roff_ccond, NULL, NULL, 0, NULL },
204 { NULL, roff_userdef, NULL, NULL, 0, NULL },
205 };
206
207 /* Array of injected predefined strings. */
208 #define PREDEFS_MAX 38
209 static const struct predef predefs[PREDEFS_MAX] = {
210 #include "predefs.in"
211 };
212
213 static void roff_free1(struct roff *);
214 static enum rofft roff_hash_find(const char *, size_t);
215 static void roff_hash_init(void);
216 static void roffnode_cleanscope(struct roff *);
217 static void roffnode_push(struct roff *, enum rofft,
218 const char *, int, int);
219 static void roffnode_pop(struct roff *);
220 static enum rofft roff_parse(struct roff *, const char *, int *);
221
222 /* See roff_hash_find() */
223 #define ROFF_HASH(p) (p[0] - ASCII_LO)
224
225 static void
226 roff_hash_init(void)
227 {
228 struct roffmac *n;
229 int buc, i;
230
231 for (i = 0; i < (int)ROFF_USERDEF; i++) {
232 assert(roffs[i].name[0] >= ASCII_LO);
233 assert(roffs[i].name[0] <= ASCII_HI);
234
235 buc = ROFF_HASH(roffs[i].name);
236
237 if (NULL != (n = hash[buc])) {
238 for ( ; n->next; n = n->next)
239 /* Do nothing. */ ;
240 n->next = &roffs[i];
241 } else
242 hash[buc] = &roffs[i];
243 }
244 }
245
246 /*
247 * Look up a roff token by its name. Returns ROFF_MAX if no macro by
248 * the nil-terminated string name could be found.
249 */
250 static enum rofft
251 roff_hash_find(const char *p, size_t s)
252 {
253 int buc;
254 struct roffmac *n;
255
256 /*
257 * libroff has an extremely simple hashtable, for the time
258 * being, which simply keys on the first character, which must
259 * be printable, then walks a chain. It works well enough until
260 * optimised.
261 */
262
263 if (p[0] < ASCII_LO || p[0] > ASCII_HI)
264 return(ROFF_MAX);
265
266 buc = ROFF_HASH(p);
267
268 if (NULL == (n = hash[buc]))
269 return(ROFF_MAX);
270 for ( ; n; n = n->next)
271 if (0 == strncmp(n->name, p, s) && '\0' == n->name[(int)s])
272 return((enum rofft)(n - roffs));
273
274 return(ROFF_MAX);
275 }
276
277
278 /*
279 * Pop the current node off of the stack of roff instructions currently
280 * pending.
281 */
282 static void
283 roffnode_pop(struct roff *r)
284 {
285 struct roffnode *p;
286
287 assert(r->last);
288 p = r->last;
289
290 r->last = r->last->parent;
291 free(p->name);
292 free(p->end);
293 free(p);
294 }
295
296
297 /*
298 * Push a roff node onto the instruction stack. This must later be
299 * removed with roffnode_pop().
300 */
301 static void
302 roffnode_push(struct roff *r, enum rofft tok, const char *name,
303 int line, int col)
304 {
305 struct roffnode *p;
306
307 p = mandoc_calloc(1, sizeof(struct roffnode));
308 p->tok = tok;
309 if (name)
310 p->name = mandoc_strdup(name);
311 p->parent = r->last;
312 p->line = line;
313 p->col = col;
314 p->rule = p->parent ? p->parent->rule : ROFFRULE_DENY;
315
316 r->last = p;
317 }
318
319
320 static void
321 roff_free1(struct roff *r)
322 {
323 struct tbl_node *t;
324 struct eqn_node *e;
325
326 while (NULL != (t = r->first_tbl)) {
327 r->first_tbl = t->next;
328 tbl_free(t);
329 }
330
331 r->first_tbl = r->last_tbl = r->tbl = NULL;
332
333 while (NULL != (e = r->first_eqn)) {
334 r->first_eqn = e->next;
335 eqn_free(e);
336 }
337
338 r->first_eqn = r->last_eqn = r->eqn = NULL;
339
340 while (r->last)
341 roffnode_pop(r);
342
343 roff_freestr(r);
344 }
345
346
347 void
348 roff_reset(struct roff *r)
349 {
350 int i;
351
352 roff_free1(r);
353
354 for (i = 0; i < PREDEFS_MAX; i++)
355 roff_setstr(r, predefs[i].name, predefs[i].str, 0);
356 }
357
358
359 void
360 roff_free(struct roff *r)
361 {
362
363 roff_free1(r);
364 free(r);
365 }
366
367
368 struct roff *
369 roff_alloc(struct regset *regs, struct mparse *parse)
370 {
371 struct roff *r;
372 int i;
373
374 r = mandoc_calloc(1, sizeof(struct roff));
375 r->regs = regs;
376 r->parse = parse;
377 r->rstackpos = -1;
378
379 roff_hash_init();
380
381 for (i = 0; i < PREDEFS_MAX; i++)
382 roff_setstr(r, predefs[i].name, predefs[i].str, 0);
383
384 return(r);
385 }
386
387
388 /*
389 * Pre-filter each and every line for reserved words (one beginning with
390 * `\*', e.g., `\*(ab'). These must be handled before the actual line
391 * is processed.
392 */
393 static int
394 roff_res(struct roff *r, char **bufp, size_t *szp, int ln, int pos)
395 {
396 const char *stesc; /* start of an escape sequence ('\\') */
397 const char *stnam; /* start of the name, after "[(*" */
398 const char *cp; /* end of the name, e.g. before ']' */
399 const char *res; /* the string to be substituted */
400 int i, maxl;
401 size_t nsz;
402 char *n;
403
404 /* Search for a leading backslash and save a pointer to it. */
405
406 cp = *bufp + pos;
407 while (NULL != (cp = strchr(cp, '\\'))) {
408 stesc = cp++;
409
410 /*
411 * The second character must be an asterisk.
412 * If it isn't, skip it anyway: It is escaped,
413 * so it can't start another escape sequence.
414 */
415
416 if ('\0' == *cp)
417 return(1);
418 if ('*' != *cp++)
419 continue;
420
421 /*
422 * The third character decides the length
423 * of the name of the string.
424 * Save a pointer to the name.
425 */
426
427 switch (*cp) {
428 case ('\0'):
429 return(1);
430 case ('('):
431 cp++;
432 maxl = 2;
433 break;
434 case ('['):
435 cp++;
436 maxl = 0;
437 break;
438 default:
439 maxl = 1;
440 break;
441 }
442 stnam = cp;
443
444 /* Advance to the end of the name. */
445
446 for (i = 0; 0 == maxl || i < maxl; i++, cp++) {
447 if ('\0' == *cp)
448 return(1); /* Error. */
449 if (0 == maxl && ']' == *cp)
450 break;
451 }
452
453 /*
454 * Retrieve the replacement string; if it is
455 * undefined, resume searching for escapes.
456 */
457
458 res = roff_getstrn(r, stnam, (size_t)i);
459
460 if (NULL == res) {
461 /* TODO: keep track of the correct position. */
462 mandoc_msg(MANDOCERR_BADESCAPE, r->parse, ln, pos, NULL);
463 res = "";
464 }
465
466 /* Replace the escape sequence by the string. */
467
468 nsz = *szp + strlen(res) + 1;
469 n = mandoc_malloc(nsz);
470
471 strlcpy(n, *bufp, (size_t)(stesc - *bufp + 1));
472 strlcat(n, res, nsz);
473 strlcat(n, cp + (maxl ? 0 : 1), nsz);
474
475 free(*bufp);
476
477 *bufp = n;
478 *szp = nsz;
479 return(0);
480 }
481
482 return(1);
483 }
484
485
486 enum rofferr
487 roff_parseln(struct roff *r, int ln, char **bufp,
488 size_t *szp, int pos, int *offs)
489 {
490 enum rofft t;
491 enum rofferr e;
492 int ppos, ctl;
493
494 /*
495 * Run the reserved-word filter only if we have some reserved
496 * words to fill in.
497 */
498
499 if (r->first_string && ! roff_res(r, bufp, szp, ln, pos))
500 return(ROFF_REPARSE);
501
502 ppos = pos;
503 ctl = mandoc_getcontrol(*bufp, &pos);
504
505 /*
506 * First, if a scope is open and we're not a macro, pass the
507 * text through the macro's filter. If a scope isn't open and
508 * we're not a macro, just let it through.
509 * Finally, if there's an equation scope open, divert it into it
510 * no matter our state.
511 */
512
513 if (r->last && ! ctl) {
514 t = r->last->tok;
515 assert(roffs[t].text);
516 e = (*roffs[t].text)
517 (r, t, bufp, szp, ln, pos, pos, offs);
518 assert(ROFF_IGN == e || ROFF_CONT == e);
519 if (ROFF_CONT != e)
520 return(e);
521 if (r->eqn)
522 return(eqn_read(&r->eqn, ln, *bufp, pos, offs));
523 if (r->tbl)
524 return(tbl_read(r->tbl, ln, *bufp, pos));
525 return(ROFF_CONT);
526 } else if ( ! ctl) {
527 if (r->eqn)
528 return(eqn_read(&r->eqn, ln, *bufp, pos, offs));
529 if (r->tbl)
530 return(tbl_read(r->tbl, ln, *bufp, pos));
531 return(ROFF_CONT);
532 } else if (r->eqn)
533 return(eqn_read(&r->eqn, ln, *bufp, ppos, offs));
534
535 /*
536 * If a scope is open, go to the child handler for that macro,
537 * as it may want to preprocess before doing anything with it.
538 * Don't do so if an equation is open.
539 */
540
541 if (r->last) {
542 t = r->last->tok;
543 assert(roffs[t].sub);
544 return((*roffs[t].sub)
545 (r, t, bufp, szp,
546 ln, ppos, pos, offs));
547 }
548
549 /*
550 * Lastly, as we've no scope open, try to look up and execute
551 * the new macro. If no macro is found, simply return and let
552 * the compilers handle it.
553 */
554
555 if (ROFF_MAX == (t = roff_parse(r, *bufp, &pos)))
556 return(ROFF_CONT);
557
558 assert(roffs[t].proc);
559 return((*roffs[t].proc)
560 (r, t, bufp, szp,
561 ln, ppos, pos, offs));
562 }
563
564
565 void
566 roff_endparse(struct roff *r)
567 {
568
569 if (r->last)
570 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
571 r->last->line, r->last->col, NULL);
572
573 if (r->eqn) {
574 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
575 r->eqn->eqn.line, r->eqn->eqn.pos, NULL);
576 eqn_end(r->eqn);
577 r->eqn = NULL;
578 }
579
580 if (r->tbl) {
581 mandoc_msg(MANDOCERR_SCOPEEXIT, r->parse,
582 r->tbl->line, r->tbl->pos, NULL);
583 tbl_end(r->tbl);
584 r->tbl = NULL;
585 }
586 }
587
588 /*
589 * Parse a roff node's type from the input buffer. This must be in the
590 * form of ".foo xxx" in the usual way.
591 */
592 static enum rofft
593 roff_parse(struct roff *r, const char *buf, int *pos)
594 {
595 const char *mac;
596 size_t maclen;
597 enum rofft t;
598
599 if ('\0' == buf[*pos] || '"' == buf[*pos] ||
600 '\t' == buf[*pos] || ' ' == buf[*pos])
601 return(ROFF_MAX);
602
603 /*
604 * We stop the macro parse at an escape, tab, space, or nil.
605 * However, `\}' is also a valid macro, so make sure we don't
606 * clobber it by seeing the `\' as the end of token.
607 */
608
609 mac = buf + *pos;
610 maclen = strcspn(mac + 1, " \\\t\0") + 1;
611
612 t = (r->current_string = roff_getstrn(r, mac, maclen))
613 ? ROFF_USERDEF : roff_hash_find(mac, maclen);
614
615 *pos += (int)maclen;
616
617 while (buf[*pos] && ' ' == buf[*pos])
618 (*pos)++;
619
620 return(t);
621 }
622
623 /* ARGSUSED */
624 static enum rofferr
625 roff_cblock(ROFF_ARGS)
626 {
627
628 /*
629 * A block-close `..' should only be invoked as a child of an
630 * ignore macro, otherwise raise a warning and just ignore it.
631 */
632
633 if (NULL == r->last) {
634 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
635 return(ROFF_IGN);
636 }
637
638 switch (r->last->tok) {
639 case (ROFF_am):
640 /* FALLTHROUGH */
641 case (ROFF_ami):
642 /* FALLTHROUGH */
643 case (ROFF_am1):
644 /* FALLTHROUGH */
645 case (ROFF_de):
646 /* ROFF_de1 is remapped to ROFF_de in roff_block(). */
647 /* FALLTHROUGH */
648 case (ROFF_dei):
649 /* FALLTHROUGH */
650 case (ROFF_ig):
651 break;
652 default:
653 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
654 return(ROFF_IGN);
655 }
656
657 if ((*bufp)[pos])
658 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
659
660 roffnode_pop(r);
661 roffnode_cleanscope(r);
662 return(ROFF_IGN);
663
664 }
665
666
667 static void
668 roffnode_cleanscope(struct roff *r)
669 {
670
671 while (r->last) {
672 if (--r->last->endspan < 0)
673 break;
674 roffnode_pop(r);
675 }
676 }
677
678
679 /* ARGSUSED */
680 static enum rofferr
681 roff_ccond(ROFF_ARGS)
682 {
683
684 if (NULL == r->last) {
685 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
686 return(ROFF_IGN);
687 }
688
689 switch (r->last->tok) {
690 case (ROFF_el):
691 /* FALLTHROUGH */
692 case (ROFF_ie):
693 /* FALLTHROUGH */
694 case (ROFF_if):
695 break;
696 default:
697 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
698 return(ROFF_IGN);
699 }
700
701 if (r->last->endspan > -1) {
702 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
703 return(ROFF_IGN);
704 }
705
706 if ((*bufp)[pos])
707 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
708
709 roffnode_pop(r);
710 roffnode_cleanscope(r);
711 return(ROFF_IGN);
712 }
713
714
715 /* ARGSUSED */
716 static enum rofferr
717 roff_block(ROFF_ARGS)
718 {
719 int sv;
720 size_t sz;
721 char *name;
722
723 name = NULL;
724
725 if (ROFF_ig != tok) {
726 if ('\0' == (*bufp)[pos]) {
727 mandoc_msg(MANDOCERR_NOARGS, r->parse, ln, ppos, NULL);
728 return(ROFF_IGN);
729 }
730
731 /*
732 * Re-write `de1', since we don't really care about
733 * groff's strange compatibility mode, into `de'.
734 */
735
736 if (ROFF_de1 == tok)
737 tok = ROFF_de;
738 if (ROFF_de == tok)
739 name = *bufp + pos;
740 else
741 mandoc_msg(MANDOCERR_REQUEST, r->parse, ln, ppos,
742 roffs[tok].name);
743
744 while ((*bufp)[pos] && ! isspace((unsigned char)(*bufp)[pos]))
745 pos++;
746
747 while (isspace((unsigned char)(*bufp)[pos]))
748 (*bufp)[pos++] = '\0';
749 }
750
751 roffnode_push(r, tok, name, ln, ppos);
752
753 /*
754 * At the beginning of a `de' macro, clear the existing string
755 * with the same name, if there is one. New content will be
756 * added from roff_block_text() in multiline mode.
757 */
758
759 if (ROFF_de == tok)
760 roff_setstr(r, name, "", 0);
761
762 if ('\0' == (*bufp)[pos])
763 return(ROFF_IGN);
764
765 /* If present, process the custom end-of-line marker. */
766
767 sv = pos;
768 while ((*bufp)[pos] && ! isspace((unsigned char)(*bufp)[pos]))
769 pos++;
770
771 /*
772 * Note: groff does NOT like escape characters in the input.
773 * Instead of detecting this, we're just going to let it fly and
774 * to hell with it.
775 */
776
777 assert(pos > sv);
778 sz = (size_t)(pos - sv);
779
780 if (1 == sz && '.' == (*bufp)[sv])
781 return(ROFF_IGN);
782
783 r->last->end = mandoc_malloc(sz + 1);
784
785 memcpy(r->last->end, *bufp + sv, sz);
786 r->last->end[(int)sz] = '\0';
787
788 if ((*bufp)[pos])
789 mandoc_msg(MANDOCERR_ARGSLOST, r->parse, ln, pos, NULL);
790
791 return(ROFF_IGN);
792 }
793
794
795 /* ARGSUSED */
796 static enum rofferr
797 roff_block_sub(ROFF_ARGS)
798 {
799 enum rofft t;
800 int i, j;
801
802 /*
803 * First check whether a custom macro exists at this level. If
804 * it does, then check against it. This is some of groff's
805 * stranger behaviours. If we encountered a custom end-scope
806 * tag and that tag also happens to be a "real" macro, then we
807 * need to try interpreting it again as a real macro. If it's
808 * not, then return ignore. Else continue.
809 */
810
811 if (r->last->end) {
812 for (i = pos, j = 0; r->last->end[j]; j++, i++)
813 if ((*bufp)[i] != r->last->end[j])
814 break;
815
816 if ('\0' == r->last->end[j] &&
817 ('\0' == (*bufp)[i] ||
818 ' ' == (*bufp)[i] ||
819 '\t' == (*bufp)[i])) {
820 roffnode_pop(r);
821 roffnode_cleanscope(r);
822
823 while (' ' == (*bufp)[i] || '\t' == (*bufp)[i])
824 i++;
825
826 pos = i;
827 if (ROFF_MAX != roff_parse(r, *bufp, &pos))
828 return(ROFF_RERUN);
829 return(ROFF_IGN);
830 }
831 }
832
833 /*
834 * If we have no custom end-query or lookup failed, then try
835 * pulling it out of the hashtable.
836 */
837
838 t = roff_parse(r, *bufp, &pos);
839
840 /*
841 * Macros other than block-end are only significant
842 * in `de' blocks; elsewhere, simply throw them away.
843 */
844 if (ROFF_cblock != t) {
845 if (ROFF_de == tok)
846 roff_setstr(r, r->last->name, *bufp + ppos, 1);
847 return(ROFF_IGN);
848 }
849
850 assert(roffs[t].proc);
851 return((*roffs[t].proc)(r, t, bufp, szp,
852 ln, ppos, pos, offs));
853 }
854
855
856 /* ARGSUSED */
857 static enum rofferr
858 roff_block_text(ROFF_ARGS)
859 {
860
861 if (ROFF_de == tok)
862 roff_setstr(r, r->last->name, *bufp + pos, 1);
863
864 return(ROFF_IGN);
865 }
866
867
868 /* ARGSUSED */
869 static enum rofferr
870 roff_cond_sub(ROFF_ARGS)
871 {
872 enum rofft t;
873 enum roffrule rr;
874 char *ep;
875
876 rr = r->last->rule;
877 roffnode_cleanscope(r);
878
879 /*
880 * If the macro is unknown, first check if it contains a closing
881 * delimiter `\}'. If it does, close out our scope and return
882 * the currently-scoped rule (ignore or continue). Else, drop
883 * into the currently-scoped rule.
884 */
885
886 if (ROFF_MAX == (t = roff_parse(r, *bufp, &pos))) {
887 ep = &(*bufp)[pos];
888 for ( ; NULL != (ep = strchr(ep, '\\')); ep++) {
889 ep++;
890 if ('}' != *ep)
891 continue;
892
893 /*
894 * Make the \} go away.
895 * This is a little haphazard, as it's not quite
896 * clear how nroff does this.
897 * If we're at the end of line, then just chop
898 * off the \} and resize the buffer.
899 * If we aren't, then conver it to spaces.
900 */
901
902 if ('\0' == *(ep + 1)) {
903 *--ep = '\0';
904 *szp -= 2;
905 } else
906 *(ep - 1) = *ep = ' ';
907
908 roff_ccond(r, ROFF_ccond, bufp, szp,
909 ln, pos, pos + 2, offs);
910 break;
911 }
912 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
913 }
914
915 /*
916 * A denied conditional must evaluate its children if and only
917 * if they're either structurally required (such as loops and
918 * conditionals) or a closing macro.
919 */
920
921 if (ROFFRULE_DENY == rr)
922 if ( ! (ROFFMAC_STRUCT & roffs[t].flags))
923 if (ROFF_ccond != t)
924 return(ROFF_IGN);
925
926 assert(roffs[t].proc);
927 return((*roffs[t].proc)(r, t, bufp, szp,
928 ln, ppos, pos, offs));
929 }
930
931 /* ARGSUSED */
932 static enum rofferr
933 roff_cond_text(ROFF_ARGS)
934 {
935 char *ep;
936 enum roffrule rr;
937
938 rr = r->last->rule;
939 roffnode_cleanscope(r);
940
941 ep = &(*bufp)[pos];
942 for ( ; NULL != (ep = strchr(ep, '\\')); ep++) {
943 ep++;
944 if ('}' != *ep)
945 continue;
946 *ep = '&';
947 roff_ccond(r, ROFF_ccond, bufp, szp,
948 ln, pos, pos + 2, offs);
949 }
950 return(ROFFRULE_DENY == rr ? ROFF_IGN : ROFF_CONT);
951 }
952
953 static enum roffrule
954 roff_evalcond(const char *v, int *pos)
955 {
956
957 switch (v[*pos]) {
958 case ('n'):
959 (*pos)++;
960 return(ROFFRULE_ALLOW);
961 case ('e'):
962 /* FALLTHROUGH */
963 case ('o'):
964 /* FALLTHROUGH */
965 case ('t'):
966 (*pos)++;
967 return(ROFFRULE_DENY);
968 default:
969 break;
970 }
971
972 while (v[*pos] && ' ' != v[*pos])
973 (*pos)++;
974 return(ROFFRULE_DENY);
975 }
976
977 /* ARGSUSED */
978 static enum rofferr
979 roff_line_ignore(ROFF_ARGS)
980 {
981
982 if (ROFF_it == tok)
983 mandoc_msg(MANDOCERR_REQUEST, r->parse, ln, ppos, "it");
984
985 return(ROFF_IGN);
986 }
987
988 /* ARGSUSED */
989 static enum rofferr
990 roff_cond(ROFF_ARGS)
991 {
992 int sv;
993 enum roffrule rule;
994
995 /*
996 * An `.el' has no conditional body: it will consume the value
997 * of the current rstack entry set in prior `ie' calls or
998 * defaults to DENY.
999 *
1000 * If we're not an `el', however, then evaluate the conditional.
1001 */
1002
1003 rule = ROFF_el == tok ?
1004 (r->rstackpos < 0 ?
1005 ROFFRULE_DENY : r->rstack[r->rstackpos--]) :
1006 roff_evalcond(*bufp, &pos);
1007
1008 sv = pos;
1009 while (' ' == (*bufp)[pos])
1010 pos++;
1011
1012 /*
1013 * Roff is weird. If we have just white-space after the
1014 * conditional, it's considered the BODY and we exit without
1015 * really doing anything. Warn about this. It's probably
1016 * wrong.
1017 */
1018
1019 if ('\0' == (*bufp)[pos] && sv != pos) {
1020 mandoc_msg(MANDOCERR_NOARGS, r->parse, ln, ppos, NULL);
1021 return(ROFF_IGN);
1022 }
1023
1024 roffnode_push(r, tok, NULL, ln, ppos);
1025
1026 r->last->rule = rule;
1027
1028 /*
1029 * An if-else will put the NEGATION of the current evaluated
1030 * conditional into the stack of rules.
1031 */
1032
1033 if (ROFF_ie == tok) {
1034 if (r->rstackpos == RSTACK_MAX - 1) {
1035 mandoc_msg(MANDOCERR_MEM,
1036 r->parse, ln, ppos, NULL);
1037 return(ROFF_ERR);
1038 }
1039 r->rstack[++r->rstackpos] =
1040 ROFFRULE_DENY == r->last->rule ?
1041 ROFFRULE_ALLOW : ROFFRULE_DENY;
1042 }
1043
1044 /* If the parent has false as its rule, then so do we. */
1045
1046 if (r->last->parent && ROFFRULE_DENY == r->last->parent->rule)
1047 r->last->rule = ROFFRULE_DENY;
1048
1049 /*
1050 * Determine scope. If we're invoked with "\{" trailing the
1051 * conditional, then we're in a multiline scope. Else our scope
1052 * expires on the next line.
1053 */
1054
1055 r->last->endspan = 1;
1056
1057 if ('\\' == (*bufp)[pos] && '{' == (*bufp)[pos + 1]) {
1058 r->last->endspan = -1;
1059 pos += 2;
1060 }
1061
1062 /*
1063 * If there are no arguments on the line, the next-line scope is
1064 * assumed.
1065 */
1066
1067 if ('\0' == (*bufp)[pos])
1068 return(ROFF_IGN);
1069
1070 /* Otherwise re-run the roff parser after recalculating. */
1071
1072 *offs = pos;
1073 return(ROFF_RERUN);
1074 }
1075
1076
1077 /* ARGSUSED */
1078 static enum rofferr
1079 roff_ds(ROFF_ARGS)
1080 {
1081 char *name, *string;
1082
1083 /*
1084 * A symbol is named by the first word following the macro
1085 * invocation up to a space. Its value is anything after the
1086 * name's trailing whitespace and optional double-quote. Thus,
1087 *
1088 * [.ds foo "bar " ]
1089 *
1090 * will have `bar " ' as its value.
1091 */
1092
1093 string = *bufp + pos;
1094 name = roff_getname(r, &string, ln, pos);
1095 if ('\0' == *name)
1096 return(ROFF_IGN);
1097
1098 /* Read past initial double-quote. */
1099 if ('"' == *string)
1100 string++;
1101
1102 /* The rest is the value. */
1103 roff_setstr(r, name, string, 0);
1104 return(ROFF_IGN);
1105 }
1106
1107
1108 /* ARGSUSED */
1109 static enum rofferr
1110 roff_nr(ROFF_ARGS)
1111 {
1112 const char *key;
1113 char *val;
1114 int iv;
1115 struct reg *rg;
1116
1117 val = *bufp + pos;
1118 key = roff_getname(r, &val, ln, pos);
1119 rg = r->regs->regs;
1120
1121 if (0 == strcmp(key, "nS")) {
1122 rg[(int)REG_nS].set = 1;
1123 if ((iv = mandoc_strntou(val, strlen(val), 10)) >= 0)
1124 rg[REG_nS].v.u = (unsigned)iv;
1125 else
1126 rg[(int)REG_nS].v.u = 0u;
1127 }
1128
1129 return(ROFF_IGN);
1130 }
1131
1132 /* ARGSUSED */
1133 static enum rofferr
1134 roff_rm(ROFF_ARGS)
1135 {
1136 const char *name;
1137 char *cp;
1138
1139 cp = *bufp + pos;
1140 while ('\0' != *cp) {
1141 name = roff_getname(r, &cp, ln, (int)(cp - *bufp));
1142 if ('\0' != *name)
1143 roff_setstr(r, name, NULL, 0);
1144 }
1145 return(ROFF_IGN);
1146 }
1147
1148 /* ARGSUSED */
1149 static enum rofferr
1150 roff_TE(ROFF_ARGS)
1151 {
1152
1153 if (NULL == r->tbl)
1154 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1155 else
1156 tbl_end(r->tbl);
1157
1158 r->tbl = NULL;
1159 return(ROFF_IGN);
1160 }
1161
1162 /* ARGSUSED */
1163 static enum rofferr
1164 roff_T_(ROFF_ARGS)
1165 {
1166
1167 if (NULL == r->tbl)
1168 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1169 else
1170 tbl_restart(ppos, ln, r->tbl);
1171
1172 return(ROFF_IGN);
1173 }
1174
1175 /* ARGSUSED */
1176 static enum rofferr
1177 roff_EQ(ROFF_ARGS)
1178 {
1179 struct eqn_node *e;
1180
1181 assert(NULL == r->eqn);
1182 e = eqn_alloc(ppos, ln, r->parse);
1183
1184 if (r->last_eqn)
1185 r->last_eqn->next = e;
1186 else
1187 r->first_eqn = r->last_eqn = e;
1188
1189 r->eqn = r->last_eqn = e;
1190 return(ROFF_IGN);
1191 }
1192
1193 /* ARGSUSED */
1194 static enum rofferr
1195 roff_EN(ROFF_ARGS)
1196 {
1197
1198 mandoc_msg(MANDOCERR_NOSCOPE, r->parse, ln, ppos, NULL);
1199 return(ROFF_IGN);
1200 }
1201
1202 /* ARGSUSED */
1203 static enum rofferr
1204 roff_TS(ROFF_ARGS)
1205 {
1206 struct tbl_node *t;
1207
1208 if (r->tbl) {
1209 mandoc_msg(MANDOCERR_SCOPEBROKEN, r->parse, ln, ppos, NULL);
1210 tbl_end(r->tbl);
1211 }
1212
1213 t = tbl_alloc(ppos, ln, r->parse);
1214
1215 if (r->last_tbl)
1216 r->last_tbl->next = t;
1217 else
1218 r->first_tbl = r->last_tbl = t;
1219
1220 r->tbl = r->last_tbl = t;
1221 return(ROFF_IGN);
1222 }
1223
1224 /* ARGSUSED */
1225 static enum rofferr
1226 roff_so(ROFF_ARGS)
1227 {
1228 char *name;
1229
1230 mandoc_msg(MANDOCERR_SO, r->parse, ln, ppos, NULL);
1231
1232 /*
1233 * Handle `so'. Be EXTREMELY careful, as we shouldn't be
1234 * opening anything that's not in our cwd or anything beneath
1235 * it. Thus, explicitly disallow traversing up the file-system
1236 * or using absolute paths.
1237 */
1238
1239 name = *bufp + pos;
1240 if ('/' == *name || strstr(name, "../") || strstr(name, "/..")) {
1241 mandoc_msg(MANDOCERR_SOPATH, r->parse, ln, pos, NULL);
1242 return(ROFF_ERR);
1243 }
1244
1245 *offs = pos;
1246 return(ROFF_SO);
1247 }
1248
1249 /* ARGSUSED */
1250 static enum rofferr
1251 roff_userdef(ROFF_ARGS)
1252 {
1253 const char *arg[9];
1254 char *cp, *n1, *n2;
1255 int i;
1256
1257 /*
1258 * Collect pointers to macro argument strings
1259 * and null-terminate them.
1260 */
1261 cp = *bufp + pos;
1262 for (i = 0; i < 9; i++)
1263 arg[i] = '\0' == *cp ? "" :
1264 mandoc_getarg(r->parse, &cp, ln, &pos);
1265
1266 /*
1267 * Expand macro arguments.
1268 */
1269 *szp = 0;
1270 n1 = cp = mandoc_strdup(r->current_string);
1271 while (NULL != (cp = strstr(cp, "\\$"))) {
1272 i = cp[2] - '1';
1273 if (0 > i || 8 < i) {
1274 /* Not an argument invocation. */
1275 cp += 2;
1276 continue;
1277 }
1278
1279 *szp = strlen(n1) - 3 + strlen(arg[i]) + 1;
1280 n2 = mandoc_malloc(*szp);
1281
1282 strlcpy(n2, n1, (size_t)(cp - n1 + 1));
1283 strlcat(n2, arg[i], *szp);
1284 strlcat(n2, cp + 3, *szp);
1285
1286 cp = n2 + (cp - n1);
1287 free(n1);
1288 n1 = n2;
1289 }
1290
1291 /*
1292 * Replace the macro invocation
1293 * by the expanded macro.
1294 */
1295 free(*bufp);
1296 *bufp = n1;
1297 if (0 == *szp)
1298 *szp = strlen(*bufp) + 1;
1299
1300 return(*szp > 1 && '\n' == (*bufp)[(int)*szp - 2] ?
1301 ROFF_REPARSE : ROFF_APPEND);
1302 }
1303
1304 static char *
1305 roff_getname(struct roff *r, char **cpp, int ln, int pos)
1306 {
1307 char *name, *cp;
1308
1309 name = *cpp;
1310 if ('\0' == *name)
1311 return(name);
1312
1313 /* Read until end of name. */
1314 for (cp = name; '\0' != *cp && ' ' != *cp; cp++) {
1315 if ('\\' != *cp)
1316 continue;
1317 cp++;
1318 if ('\\' == *cp)
1319 continue;
1320 mandoc_msg(MANDOCERR_NAMESC, r->parse, ln, pos, NULL);
1321 *cp = '\0';
1322 name = cp;
1323 }
1324
1325 /* Nil-terminate name. */
1326 if ('\0' != *cp)
1327 *(cp++) = '\0';
1328
1329 /* Read past spaces. */
1330 while (' ' == *cp)
1331 cp++;
1332
1333 *cpp = cp;
1334 return(name);
1335 }
1336
1337 /*
1338 * Store *string into the user-defined string called *name.
1339 * In multiline mode, append to an existing entry and append '\n';
1340 * else replace the existing entry, if there is one.
1341 * To clear an existing entry, call with (*r, *name, NULL, 0).
1342 */
1343 static void
1344 roff_setstr(struct roff *r, const char *name, const char *string,
1345 int multiline)
1346 {
1347 struct roffstr *n;
1348 char *c;
1349 size_t oldch, newch;
1350
1351 /* Search for an existing string with the same name. */
1352 n = r->first_string;
1353 while (n && strcmp(name, n->name))
1354 n = n->next;
1355
1356 if (NULL == n) {
1357 /* Create a new string table entry. */
1358 n = mandoc_malloc(sizeof(struct roffstr));
1359 n->name = mandoc_strdup(name);
1360 n->string = NULL;
1361 n->next = r->first_string;
1362 r->first_string = n;
1363 } else if (0 == multiline) {
1364 /* In multiline mode, append; else replace. */
1365 free(n->string);
1366 n->string = NULL;
1367 }
1368
1369 if (NULL == string)
1370 return;
1371
1372 /*
1373 * One additional byte for the '\n' in multiline mode,
1374 * and one for the terminating '\0'.
1375 */
1376 newch = strlen(string) + (multiline ? 2u : 1u);
1377 if (NULL == n->string) {
1378 n->string = mandoc_malloc(newch);
1379 *n->string = '\0';
1380 oldch = 0;
1381 } else {
1382 oldch = strlen(n->string);
1383 n->string = mandoc_realloc(n->string, oldch + newch);
1384 }
1385
1386 /* Skip existing content in the destination buffer. */
1387 c = n->string + (int)oldch;
1388
1389 /* Append new content to the destination buffer. */
1390 while (*string) {
1391 /*
1392 * Rudimentary roff copy mode:
1393 * Handle escaped backslashes.
1394 */
1395 if ('\\' == *string && '\\' == *(string + 1))
1396 string++;
1397 *c++ = *string++;
1398 }
1399
1400 /* Append terminating bytes. */
1401 if (multiline)
1402 *c++ = '\n';
1403 *c = '\0';
1404 }
1405
1406 static const char *
1407 roff_getstrn(const struct roff *r, const char *name, size_t len)
1408 {
1409 const struct roffstr *n;
1410
1411 n = r->first_string;
1412 while (n && (strncmp(name, n->name, len) || '\0' != n->name[(int)len]))
1413 n = n->next;
1414
1415 return(n ? n->string : NULL);
1416 }
1417
1418 static void
1419 roff_freestr(struct roff *r)
1420 {
1421 struct roffstr *n, *nn;
1422
1423 for (n = r->first_string; n; n = nn) {
1424 free(n->name);
1425 free(n->string);
1426 nn = n->next;
1427 free(n);
1428 }
1429
1430 r->first_string = NULL;
1431 }
1432
1433 const struct tbl_span *
1434 roff_span(const struct roff *r)
1435 {
1436
1437 return(r->tbl ? tbl_span(r->tbl) : NULL);
1438 }
1439
1440 const struct eqn *
1441 roff_eqn(const struct roff *r)
1442 {
1443
1444 return(r->last_eqn ? &r->last_eqn->eqn : NULL);
1445 }