]> diplodocus.org Git - nmh/blob - sbr/fmt_compile.c
c4476f8d12468dbdee28bf50bbe6e884dc3095a7
[nmh] / sbr / fmt_compile.c
1
2 /*
3 * fmt_compile.c -- "compile" format strings for fmt_scan
4 *
5 * This code is Copyright (c) 2002, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
8 *
9 * This code compiles the format strings (documented in mh-format(5)) into
10 * an internal form to be later processed by fmt_scan.c.
11 *
12 * What happens here is that the format strings are parsed and an array
13 * of struct format structures are returned. Each format structure is
14 * a single operation interpreted by the the routines in fmt_scan.c.
15 *
16 * There is a NOT a one-to-one correspondence between format strings and
17 * format instructions; some functions have side effects that can result
18 * in multiple instructions being generated. The exact list of instructions
19 * generated by a format string can be seem with the nmh fmttest utility.
20 *
21 * A list of format instructions can be found in fmt_compile.h.
22 *
23 * If you wish to add a new function, you will need to do the following
24 * things:
25 *
26 * - Add a new instruction to the list of instructions in fmt_compile.h.
27 * Note that test instructions (starting with FT_IF_S_NULL) have special
28 * handling, so if you are NOT writing a test function then you need
29 * to insert it into the list before that _and_ bump all of the
30 * following instruction numbers.
31 *
32 * - Add the function name to the functable[] array below, and write any
33 * special code that your function may require in terms of parsing
34 * (it very well may not need anything).
35 *
36 * - Add the code in fmt_scan.c to handle your new function.
37 *
38 * - Add code to fmttest.c to display your new function.
39 *
40 * - Document the new function in the mh-format(5) man page.
41 *
42 */
43
44 #include <h/mh.h>
45 #include <h/addrsbr.h>
46 #include <h/tws.h>
47 #include <h/fmt_scan.h>
48 #include <h/fmt_compile.h>
49 #include <h/mts.h>
50 #include <h/utils.h>
51
52 #include <curses.h>
53 #include <term.h>
54
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
57 #endif
58 #include <time.h>
59
60 /*
61 * hash table for deciding if a component is "interesting"
62 */
63 static struct comp *wantcomp[128];
64
65 static struct format *formatvec; /* array to hold formats */
66 static struct format *next_fp; /* next free format slot */
67 static struct format *fp; /* current format slot */
68 static struct comp *cm; /* most recent comp ref */
69 static struct ftable *ftbl; /* most recent func ref */
70 static int ncomp;
71 static int infunction; /* function nesting cnt */
72 static int termstatus = 0; /* 0=uninit,1=ok,-1=fail */
73 static char *termcbuf = NULL; /* Capability output str */
74 static char *termcbufp = NULL; /* Capability buf ptr */
75 static size_t termcbufsz = 0; /* Size of termcbuf */
76
77 extern struct mailname fmt_mnull;
78
79 /* ftable->type (argument type) */
80 #define TF_COMP 0 /* component expected */
81 #define TF_NUM 1 /* number expected */
82 #define TF_STR 2 /* string expected */
83 #define TF_EXPR 3 /* component or func. expected */
84 #define TF_NONE 4 /* no argument */
85 #define TF_MYBOX 5 /* special - get current user's mbox */
86 #define TF_NOW 6 /* special - get current unix time */
87 #define TF_EXPR_SV 7 /* like expr but save current str reg */
88 #define TF_NOP 8 /* like expr but no result */
89 #define TF_MYNAME 9 /* special - get current name of user */
90 #define TF_MYHOST 10 /* special - get "local" hostname */
91 #define TF_LMBOX 11 /* special - get full local mailbox */
92 #define TF_BOLD 12 /* special - enter terminal bold mode */
93 #define TF_UNDERLN 13 /* special - enter underline mode */
94 #define TF_RESET 14 /* special - reset terminal modes */
95
96 /* ftable->flags */
97 /* NB that TFL_PUTS is also used to decide whether the test
98 * in a "%<(function)..." should be a string or numeric one.
99 */
100 #define TFL_PUTS 1 /* implicit putstr if top level */
101 #define TFL_PUTN 2 /* implicit putnum if top level */
102
103 /*
104 * The functable array maps between the text names of format functions and
105 * the format instructions interpreted by the engine in fmt_scan.c.
106 *
107 * The elements of this structure are as follows:
108 *
109 * name - The name of the function as seen in the format string. This is
110 * what maps a particular function name into a format instruction.
111 * type - The type of argument this function expects. Those types are
112 * listed above (with the TF_ prefix). This affects what gets
113 * placed in the format instruction (the f_un union).
114 * f_type - The instruction corresponding to this function (from the list
115 * in fmt_compile.h).
116 * extra - Used by some functions to provide extra data to the compiler.
117 * Uses include:
118 * - Providing an alternate instruction to combine a load
119 * and test operation (see do_if()).
120 * - Passed in f_value in the format instruction to provide
121 * extra information for the engine (see FT_LV_DAT handling
122 * in fmt_scan.c).
123 * - Provide a hint as to preprocessing that is required for
124 * this instruction (see do_name()).
125 * flags - See the definitions for TFL_PUTS & TFL_PUTN above.
126 */
127
128 struct ftable {
129 char *name; /* function name */
130 char type; /* argument type */
131 char f_type; /* fmt type */
132 char extra; /* arg. type dependent extra info */
133 char flags;
134 };
135
136 static struct ftable functable[] = {
137 { "nonzero", TF_EXPR, FT_V_NE, FT_IF_V_NE, 0 },
138 { "zero", TF_EXPR, FT_V_EQ, FT_IF_V_EQ, 0 },
139 { "eq", TF_NUM, FT_V_EQ, FT_IF_V_EQ, 0 },
140 { "ne", TF_NUM, FT_V_NE, FT_IF_V_NE, 0 },
141 { "gt", TF_NUM, FT_V_GT, FT_IF_V_GT, 0 },
142 { "null", TF_EXPR, FT_S_NULL, FT_IF_S_NULL, 0 },
143 { "nonnull", TF_EXPR, FT_S_NONNULL, FT_IF_S, 0 },
144 { "match", TF_STR, FT_V_MATCH, FT_IF_MATCH, 0 },
145 { "amatch", TF_STR, FT_V_AMATCH, FT_IF_AMATCH, 0 },
146
147 { "putstr", TF_EXPR, FT_STR, 0, 0 },
148 { "putstrf", TF_EXPR, FT_STRF, 0, 0 },
149 { "putnum", TF_EXPR, FT_NUM, 0, 0 },
150 { "putnumf", TF_EXPR, FT_NUMF, 0, 0 },
151 { "putaddr", TF_STR, FT_PUTADDR, 0, 0 },
152 { "putlit", TF_EXPR, FT_STRLIT, 0, 0 },
153 { "zputlit", TF_EXPR, FT_STRLITZ, 0, 0 },
154 { "void", TF_NOP, 0, 0, 0 },
155
156 { "comp", TF_COMP, FT_LS_COMP, 0, TFL_PUTS },
157 { "lit", TF_STR, FT_LS_LIT, 0, TFL_PUTS },
158 { "getenv", TF_STR, FT_LS_GETENV, 0, TFL_PUTS },
159 { "profile", TF_STR, FT_LS_CFIND, 0, TFL_PUTS },
160 { "decodecomp", TF_COMP, FT_LS_DECODECOMP, 0, TFL_PUTS },
161 { "decode", TF_EXPR, FT_LS_DECODE, 0, TFL_PUTS },
162 { "trim", TF_EXPR, FT_LS_TRIM, 0, 0 },
163 { "compval", TF_COMP, FT_LV_COMP, 0, TFL_PUTN },
164 { "compflag", TF_COMP, FT_LV_COMPFLAG, 0, TFL_PUTN },
165 { "num", TF_NUM, FT_LV_LIT, 0, TFL_PUTN },
166 { "msg", TF_NONE, FT_LV_DAT, 0, TFL_PUTN },
167 { "cur", TF_NONE, FT_LV_DAT, 1, TFL_PUTN },
168 { "size", TF_NONE, FT_LV_DAT, 2, TFL_PUTN },
169 { "width", TF_NONE, FT_LV_DAT, 3, TFL_PUTN },
170 { "unseen", TF_NONE, FT_LV_DAT, 4, TFL_PUTN },
171 { "dat", TF_NUM, FT_LV_DAT, 0, TFL_PUTN },
172 { "strlen", TF_NONE, FT_LV_STRLEN, 0, TFL_PUTN },
173 { "me", TF_MYBOX, FT_LS_LIT, 0, TFL_PUTS },
174 { "myname", TF_MYNAME, FT_LS_LIT, 0, TFL_PUTS },
175 { "myhost", TF_MYHOST, FT_LS_LIT, 0, TFL_PUTS },
176 { "localmbox", TF_LMBOX, FT_LS_LIT, 0, TFL_PUTS },
177 { "plus", TF_NUM, FT_LV_PLUS_L, 0, TFL_PUTN },
178 { "minus", TF_NUM, FT_LV_MINUS_L, 0, TFL_PUTN },
179 { "divide", TF_NUM, FT_LV_DIVIDE_L, 0, TFL_PUTN },
180 { "modulo", TF_NUM, FT_LV_MODULO_L, 0, TFL_PUTN },
181 { "charleft", TF_NONE, FT_LV_CHAR_LEFT, 0, TFL_PUTN },
182 { "timenow", TF_NOW, FT_LV_LIT, 0, TFL_PUTN },
183
184 { "month", TF_COMP, FT_LS_MONTH, FT_PARSEDATE, TFL_PUTS },
185 { "lmonth", TF_COMP, FT_LS_LMONTH, FT_PARSEDATE, TFL_PUTS },
186 { "tzone", TF_COMP, FT_LS_ZONE, FT_PARSEDATE, TFL_PUTS },
187 { "day", TF_COMP, FT_LS_DAY, FT_PARSEDATE, TFL_PUTS },
188 { "weekday", TF_COMP, FT_LS_WEEKDAY, FT_PARSEDATE, TFL_PUTS },
189 { "tws", TF_COMP, FT_LS_822DATE, FT_PARSEDATE, TFL_PUTS },
190 { "sec", TF_COMP, FT_LV_SEC, FT_PARSEDATE, TFL_PUTN },
191 { "min", TF_COMP, FT_LV_MIN, FT_PARSEDATE, TFL_PUTN },
192 { "hour", TF_COMP, FT_LV_HOUR, FT_PARSEDATE, TFL_PUTN },
193 { "mday", TF_COMP, FT_LV_MDAY, FT_PARSEDATE, TFL_PUTN },
194 { "mon", TF_COMP, FT_LV_MON, FT_PARSEDATE, TFL_PUTN },
195 { "year", TF_COMP, FT_LV_YEAR, FT_PARSEDATE, TFL_PUTN },
196 { "yday", TF_COMP, FT_LV_YDAY, FT_PARSEDATE, TFL_PUTN },
197 { "wday", TF_COMP, FT_LV_WDAY, FT_PARSEDATE, TFL_PUTN },
198 { "zone", TF_COMP, FT_LV_ZONE, FT_PARSEDATE, TFL_PUTN },
199 { "clock", TF_COMP, FT_LV_CLOCK, FT_PARSEDATE, TFL_PUTN },
200 { "rclock", TF_COMP, FT_LV_RCLOCK, FT_PARSEDATE, TFL_PUTN },
201 { "sday", TF_COMP, FT_LV_DAYF, FT_PARSEDATE, TFL_PUTN },
202 { "szone", TF_COMP, FT_LV_ZONEF, FT_PARSEDATE, TFL_PUTN },
203 { "dst", TF_COMP, FT_LV_DST, FT_PARSEDATE, TFL_PUTN },
204 { "pretty", TF_COMP, FT_LS_PRETTY, FT_PARSEDATE, TFL_PUTS },
205 { "nodate", TF_COMP, FT_LV_COMPFLAG, FT_PARSEDATE, TFL_PUTN },
206 { "date2local", TF_COMP, FT_LOCALDATE, FT_PARSEDATE, 0 },
207 { "date2gmt", TF_COMP, FT_GMTDATE, FT_PARSEDATE, 0 },
208
209 { "pers", TF_COMP, FT_LS_PERS, FT_PARSEADDR, TFL_PUTS },
210 { "mbox", TF_COMP, FT_LS_MBOX, FT_PARSEADDR, TFL_PUTS },
211 { "host", TF_COMP, FT_LS_HOST, FT_PARSEADDR, TFL_PUTS },
212 { "path", TF_COMP, FT_LS_PATH, FT_PARSEADDR, TFL_PUTS },
213 { "gname", TF_COMP, FT_LS_GNAME, FT_PARSEADDR, TFL_PUTS },
214 { "note", TF_COMP, FT_LS_NOTE, FT_PARSEADDR, TFL_PUTS },
215 { "addr", TF_COMP, FT_LS_ADDR, FT_PARSEADDR, TFL_PUTS },
216 { "proper", TF_COMP, FT_LS_822ADDR, FT_PARSEADDR, TFL_PUTS },
217 { "type", TF_COMP, FT_LV_HOSTTYPE, FT_PARSEADDR, TFL_PUTN },
218 { "ingrp", TF_COMP, FT_LV_INGRPF, FT_PARSEADDR, TFL_PUTN },
219 { "nohost", TF_COMP, FT_LV_NOHOSTF, FT_PARSEADDR, TFL_PUTN },
220 { "formataddr", TF_EXPR_SV,FT_FORMATADDR, FT_FORMATADDR, 0 },
221 { "concataddr", TF_EXPR_SV,FT_CONCATADDR, FT_FORMATADDR, 0 },
222 { "friendly", TF_COMP, FT_LS_FRIENDLY, FT_PARSEADDR, TFL_PUTS },
223
224 { "mymbox", TF_COMP, FT_LV_COMPFLAG, FT_MYMBOX, TFL_PUTN },
225
226 { "unquote", TF_EXPR, FT_LS_UNQUOTE, 0, TFL_PUTS },
227
228 { "bold", TF_BOLD, FT_LS_LIT, 0, TFL_PUTS },
229 { "underline", TF_UNDERLN,FT_LS_LIT, 0, TFL_PUTS },
230 { "resetterm", TF_RESET, FT_LS_LIT, 0, TFL_PUTS },
231
232 { NULL, 0, 0, 0, 0 }
233 };
234
235 /*
236 * Hash function for component name. The function should be
237 * case independent and probably shouldn't involve a routine
238 * call. This function is pretty good but will not work on
239 * single character component names.
240 */
241 #define CHASH(nm) (((((nm)[0]) - ((nm)[1])) & 0x1f) + (((nm)[2]) & 0x5f))
242
243 /*
244 * Find a component in the hash table.
245 */
246 #define FINDCOMP(comp,name) \
247 for (comp = wantcomp[CHASH(name)]; \
248 comp && strcmp(comp->c_name,name); \
249 comp = comp->c_next) \
250 ;
251
252 /* Add new component to the hash table */
253 #define NEWCOMP(cm,name) do { \
254 cm = ((struct comp *) calloc(1, sizeof (struct comp)));\
255 cm->c_name = getcpy(name);\
256 cm->c_refcount++;\
257 ncomp++;\
258 i = CHASH(name);\
259 cm->c_next = wantcomp[i];\
260 wantcomp[i] = cm; \
261 } while (0)
262
263 #define NEWFMT (next_fp++)
264 #define NEW(type,fill,wid) do {\
265 fp=NEWFMT; fp->f_type=(type); fp->f_fill=(fill); fp->f_width=(wid); \
266 } while (0)
267
268 /* Add (possibly new) component to the hash table */
269 #define ADDC(name) do { \
270 FINDCOMP(cm, name);\
271 if (!cm) {\
272 NEWCOMP(cm,name);\
273 }\
274 fp->f_comp = cm; \
275 fp->f_flags |= FF_COMPREF; \
276 cm->c_refcount++; \
277 } while (0)
278
279 #define LV(type, value) do { NEW(type,0,0); fp->f_value = (value); } while (0)
280 #define LS(type, str) do { NEW(type,0,0); fp->f_text = getcpy(str); fp->f_flags |= FF_STRALLOC; } while (0)
281
282 #define PUTCOMP(comp) do { NEW(FT_COMP,0,0); ADDC(comp); } while (0)
283 #define PUTLIT(str) do { NEW(FT_LIT,0,0); fp->f_text = getcpy(str); fp->f_flags |= FF_STRALLOC; } while (0)
284 #define PUTC(c) do { NEW(FT_CHAR,0,0); fp->f_char = (c); } while (0)
285
286 static char *format_string;
287 static char *usr_fstring; /* for CERROR */
288
289 #define CERROR(str) compile_error (str, cp)
290
291 /*
292 * static prototypes
293 */
294 static struct ftable *lookup(char *);
295 static void compile_error(char *, char *);
296 static char *compile (char *);
297 static char *do_spec(char *);
298 static char *do_name(char *, int);
299 static char *do_func(char *);
300 static char *do_expr (char *, int);
301 static char *do_loop(char *);
302 static char *do_if(char *);
303 static void free_component(struct comp *);
304 static void free_comptable(void);
305 static void initialize_terminfo(void);
306 static void get_term_stringcap(struct ftable *, char *);
307 static int termbytes(int);
308
309 /*
310 * Lookup a function name in the functable
311 */
312 static struct ftable *
313 lookup(char *name)
314 {
315 register struct ftable *t = functable;
316 register char *nm;
317 register char c = *name;
318
319 while ((nm = t->name)) {
320 if (*nm == c && strcmp (nm, name) == 0)
321 return (ftbl = t);
322
323 t++;
324 }
325 return (struct ftable *) 0;
326 }
327
328
329 static void
330 compile_error(char *str, char *cp)
331 {
332 int i, errpos, errctx;
333
334 errpos = cp - format_string;
335 errctx = errpos > 20 ? 20 : errpos;
336 usr_fstring[errpos] = '\0';
337
338 for (i = errpos-errctx; i < errpos; i++) {
339 #ifdef LOCALE
340 if (iscntrl((unsigned char) usr_fstring[i]))
341 #else
342 if (usr_fstring[i] < 32)
343 #endif
344 usr_fstring[i] = '_';
345 }
346
347 advise(NULL, "\"%s\": format compile error - %s",
348 &usr_fstring[errpos-errctx], str);
349 adios (NULL, "%*s", errctx+1, "^");
350 }
351
352 /*
353 * Compile format string "fstring" into format list "fmt".
354 * Return the number of header components found in the format
355 * string.
356 */
357
358 int
359 fmt_compile(char *fstring, struct format **fmt, int reset_comptable)
360 {
361 register char *cp;
362 size_t i;
363 static int comptable_initialized = 0;
364
365 format_string = getcpy (fstring);
366 usr_fstring = fstring;
367
368 if (reset_comptable || !comptable_initialized) {
369 free_comptable();
370 comptable_initialized = 1;
371 }
372
373 memset((char *) &fmt_mnull, 0, sizeof(fmt_mnull));
374
375 /* it takes at least 4 char to generate one format so we
376 * allocate a worst-case format array using 1/4 the length
377 * of the format string. We actually need twice this much
378 * to handle both pre-processing (e.g., address parsing) and
379 * normal processing.
380 */
381 i = strlen(fstring)/2 + 1;
382 if (i==1) i++;
383 next_fp = formatvec = (struct format *)calloc ((size_t) i,
384 sizeof(struct format));
385 if (next_fp == NULL)
386 adios (NULL, "unable to allocate format storage");
387
388 infunction = 0;
389
390 cp = compile(format_string);
391 if (*cp) {
392 CERROR("extra '%>', '%|' or '%?'");
393 }
394 LV(FT_DONE, 0); /* really done */
395 *fmt = formatvec;
396
397 free(format_string);
398 return (ncomp);
399 }
400
401 static char *
402 compile (char *sp)
403 {
404 register char *cp = sp;
405 register int c;
406
407 for (;;) {
408 sp = cp;
409 while ((c = *cp) && c != '%')
410 cp++;
411 *cp = 0;
412 switch (cp-sp) {
413 case 0:
414 break;
415 case 1:
416 PUTC(*sp);
417 break;
418 default:
419 PUTLIT(sp);
420 break;
421 }
422 if (c == 0)
423 return (cp);
424
425 switch (c = *++cp) {
426 case '%':
427 PUTC (*cp);
428 cp++;
429 break;
430
431 case '|':
432 case '>':
433 case '?':
434 case ']':
435 return (cp);
436
437 case '<':
438 cp = do_if(++cp);
439 break;
440
441 case '[': /* ] */
442 cp = do_loop(++cp);
443 break;
444
445 case ';': /* comment line */
446 cp++;
447 while ((c = *cp++) && c != '\n')
448 continue;
449 break;
450
451 default:
452 cp = do_spec(cp);
453 break;
454 }
455 }
456 }
457
458
459 /*
460 * Process functions & components (handle field width here as well
461 */
462 static char *
463 do_spec(char *sp)
464 {
465 register char *cp = sp;
466 register int c;
467 #ifndef lint
468 register int ljust = 0;
469 #endif /* not lint */
470 register int wid = 0;
471 register char fill = ' ';
472
473 c = *cp++;
474 if (c == '-') {
475 ljust++;
476 c = *cp++;
477 }
478 if (c == '0') {
479 fill = c;
480 c = *cp++;
481 }
482 while (isdigit(c)) {
483 wid = wid*10 + (c - '0');
484 c = *cp++;
485 }
486 if (c == '{') {
487 cp = do_name(cp, 0);
488 if (! infunction)
489 fp->f_type = wid? FT_COMPF : FT_COMP;
490 }
491 else if (c == '(') {
492 cp = do_func(cp);
493 if (! infunction) {
494 if (ftbl->flags & TFL_PUTS) {
495 LV( wid? FT_STRF : FT_STR, ftbl->extra);
496 }
497 else if (ftbl->flags & TFL_PUTN) {
498 LV( wid? FT_NUMF : FT_NUM, ftbl->extra);
499 }
500 }
501 }
502 else {
503 CERROR("component or function name expected");
504 }
505 if (ljust)
506 wid = -wid;
507 fp->f_width = wid;
508 fp->f_fill = fill;
509
510 return (cp);
511 }
512
513 /*
514 * Process a component name. Normally this involves generating an FT_COMP
515 * instruction for the specified component. If preprocess is set, then we
516 * do some extra processing.
517 */
518 static char *
519 do_name(char *sp, int preprocess)
520 {
521 register char *cp = sp;
522 register int c;
523 register int i;
524 static int primed = 0;
525
526 while (isalnum(c = *cp++) || c == '-' || c == '_')
527 ;
528 if (c != '}') {
529 CERROR("'}' expected");
530 }
531 cp[-1] = '\0';
532 PUTCOMP(sp);
533 switch (preprocess) {
534
535 case FT_PARSEDATE:
536 if (cm->c_type & CT_ADDR) {
537 CERROR("component used as both date and address");
538 }
539 cm->c_tws = (struct tws *)
540 calloc((size_t) 1, sizeof(*cm->c_tws));
541 fp->f_type = preprocess;
542 PUTCOMP(sp);
543 cm->c_type |= CT_DATE;
544 break;
545
546 case FT_MYMBOX:
547 if (!primed) {
548 ismymbox ((struct mailname *) 0);
549 primed++;
550 }
551 /* fall through */
552 case FT_PARSEADDR:
553 if (cm->c_type & CT_DATE) {
554 CERROR("component used as both date and address");
555 }
556 cm->c_mn = &fmt_mnull;
557 fp->f_type = preprocess;
558 PUTCOMP(sp);
559 cm->c_type |= CT_ADDR;
560 break;
561
562 case FT_FORMATADDR:
563 if (cm->c_type & CT_DATE) {
564 CERROR("component used as both date and address");
565 }
566 cm->c_type |= CT_ADDR;
567 break;
568 }
569 return (cp);
570 }
571
572 /*
573 * Generate one or more instructions corresponding to the named function.
574 * The different type of function arguments are handled here.
575 */
576 static char *
577 do_func(char *sp)
578 {
579 register char *cp = sp;
580 register int c;
581 register struct ftable *t;
582 register int n;
583 int mflag; /* minus sign in NUM */
584
585 infunction++;
586
587 while (isalnum(c = *cp++))
588 ;
589 if (c != '(' && c != '{' && c != ' ' && c != ')') {
590 CERROR("'(', '{', ' ' or ')' expected");
591 }
592 cp[-1] = '\0';
593 if ((t = lookup (sp)) == 0) {
594 CERROR("unknown function");
595 }
596 if (isspace(c))
597 c = *cp++;
598
599 switch (t->type) {
600
601 case TF_COMP:
602 if (c != '{') {
603 CERROR("component name expected");
604 }
605 cp = do_name(cp, t->extra);
606 fp->f_type = t->f_type;
607 c = *cp++;
608 break;
609
610 case TF_NUM:
611 if ((mflag = (c == '-')))
612 c = *cp++;
613 n = 0;
614 while (isdigit(c)) {
615 n = n*10 + (c - '0');
616 c = *cp++;
617 }
618 if (mflag)
619 n = (-n);
620 LV(t->f_type,n);
621 break;
622
623 case TF_STR:
624 sp = cp - 1;
625 while (c && c != ')')
626 c = *cp++;
627 cp[-1] = '\0';
628 LS(t->f_type,sp);
629 break;
630
631 case TF_NONE:
632 LV(t->f_type,t->extra);
633 break;
634
635 case TF_MYBOX:
636 LS(t->f_type, getusername());
637 break;
638
639 case TF_MYNAME:
640 LS(t->f_type, getfullname());
641 break;
642
643 case TF_MYHOST:
644 LS(t->f_type, LocalName(0));
645 break;
646
647 case TF_LMBOX:
648 LS(t->f_type, getlocalmbox());
649 break;
650
651 case TF_BOLD:
652 get_term_stringcap(t, "bold");
653 break;
654
655 case TF_UNDERLN:
656 get_term_stringcap(t, "smul");
657 break;
658
659 case TF_RESET:
660 get_term_stringcap(t, "sgr0");
661 break;
662
663 case TF_NOW:
664 LV(t->f_type, time((time_t *) 0));
665 break;
666
667 case TF_EXPR_SV:
668 LV(FT_SAVESTR, 0);
669 /* fall through */
670 case TF_EXPR:
671 *--cp = c;
672 cp = do_expr(cp, t->extra);
673 LV(t->f_type, 0);
674 c = *cp++;
675 ftbl = t;
676 break;
677
678 case TF_NOP:
679 *--cp = c;
680 cp = do_expr(cp, t->extra);
681 c = *cp++;
682 ftbl = t;
683 break;
684 }
685 if (c != ')') {
686 CERROR("')' expected");
687 }
688 --infunction;
689 return (cp);
690 }
691
692 /*
693 * Handle an expression as an argument. Basically we call one of do_name(),
694 * do_func(), or do_if()
695 */
696 static char *
697 do_expr (char *sp, int preprocess)
698 {
699 register char *cp = sp;
700 register int c;
701
702 if ((c = *cp++) == '{') {
703 cp = do_name (cp, preprocess);
704 fp->f_type = FT_LS_COMP;
705 } else if (c == '(') {
706 cp = do_func (cp);
707 } else if (c == ')') {
708 return (--cp);
709 } else if (c == '%' && *cp == '<') {
710 cp = do_if (cp+1);
711 } else {
712 CERROR ("'(', '{', '%<' or ')' expected");
713 }
714 return (cp);
715 }
716
717 /*
718 * I am guessing this was for some kind of loop statement, which would have
719 * looked like %[ .... %]. It looks like the way this would have worked
720 * is that the format engine would have seen that FT_DONE had a 1 in the
721 * f_un.f_un_value and then decided whether or not to continue the loop.
722 * There is no support for this in the format engine, so right now if
723 * you try using it you will reach the FT_DONE and simply stop. I'm leaving
724 * this here in case someone wants to continue the work.
725 *
726 * Okay, got some more information on this from John L. Romine! From an
727 * email he sent to the nmh-workers mailing list on December 2, 2010, he
728 * explains it thusly:
729 *
730 * In this case (scan, formatsbr) it has to do with an extension to
731 * the mh-format syntax to allow for looping.
732 *
733 * The scan format is processed once for each message. Those #ifdef
734 * JLR changes allowed for the top part of the format file to be
735 * processed once, then a second, looping part to be processed
736 * once per message. As I recall, there were new mh-format escape
737 * sequences to delimit the loop. This would have allowed for things
738 * like per-format column headings in the scan output.
739 *
740 * Since existing format files didn't include the scan listing
741 * header (it was hard-coded in scan.c) it would not have been
742 * backward-compatible. All existing format files (including any
743 * local ones) would have needed to be changed to include the format
744 * codes for a header. The practice at the time was not to introduce
745 * incompatible changes in a minor release, and I never managed to
746 * put out a newer major release.
747 *
748 * I can see how this would work, and I suspect part of the motivation was
749 * because the format compiler routines (at the time) couldn't really be
750 * called multiple times on the same message because the memory management
751 * was so lousy. That's been reworked and things are now a lot cleaner,
752 * so I suspect if we're going to allow a format string to be used for the
753 * scan header it might be simpler to have a separate format string just
754 * for the header. But I'll leave this code in for now just in case we
755 * decide that we want some kind of looping support.
756 */
757 static char *
758 do_loop(char *sp)
759 {
760 register char *cp = sp;
761 struct format *floop;
762
763 floop = next_fp;
764 cp = compile (cp);
765 if (*cp++ != ']')
766 CERROR ("']' expected");
767
768 LV(FT_DONE, 1); /* not yet done */
769 LV(FT_GOTO, 0);
770 fp->f_skip = floop - fp; /* skip backwards */
771
772 return cp;
773 }
774
775 /*
776 * Handle an if-elsif-endif statement. Note here that the branching
777 * is handled by the f_skip member of the struct format (which is really
778 * just f_width overloaded). This number controls how far to move forward
779 * (or back) in the format instruction array.
780 */
781 static char *
782 do_if(char *sp)
783 {
784 register char *cp = sp;
785 register struct format *fexpr,
786 *fif = (struct format *)NULL;
787 register int c = '<';
788
789 for (;;) {
790 if (c == '<') { /* doing an IF */
791 if ((c = *cp++) == '{') /*}*/{
792 cp = do_name(cp, 0);
793 fp->f_type = FT_LS_COMP;
794 LV (FT_IF_S, 0);
795 }
796 else if (c == '(') {
797 cp = do_func(cp);
798 /* see if we can merge the load and the "if" */
799 if (ftbl->f_type >= IF_FUNCS)
800 fp->f_type = ftbl->extra;
801 else {
802 /* Put out a string test or a value test depending
803 * on what this function's return type is.
804 */
805 if (ftbl->flags & TFL_PUTS) {
806 LV (FT_IF_S, 0);
807 } else {
808 LV (FT_IF_V_NE, 0);
809 }
810 }
811 }
812 else {
813 CERROR("'(' or '{' expected"); /*}*/
814 }
815 }
816
817 fexpr = fp; /* loc of [ELS]IF */
818 cp = compile (cp); /* compile IF TRUE stmts */
819 if (fif)
820 fif->f_skip = next_fp - fif;
821
822 if ((c = *cp++) == '|') { /* the last ELSE */
823 LV(FT_GOTO, 0);
824 fif = fp; /* loc of GOTO */
825 fexpr->f_skip = next_fp - fexpr;
826
827 fexpr = (struct format *)NULL;/* no extra ENDIF */
828
829 cp = compile (cp); /* compile ELSE stmts */
830 fif->f_skip = next_fp - fif;
831 c = *cp++;
832 }
833 else if (c == '?') { /* another ELSIF */
834 LV(FT_GOTO, 0);
835 fif = fp; /* loc of GOTO */
836 fexpr->f_skip = next_fp - fexpr;
837
838 c = '<'; /* impersonate an IF */
839 continue;
840 }
841 break;
842 }
843
844 if (c != '>') {
845 CERROR("'>' expected.");
846 }
847
848 if (fexpr) /* IF ... [ELSIF ...] ENDIF */
849 fexpr->f_skip = next_fp - fexpr;
850
851 return (cp);
852 }
853
854 /*
855 * Free a set of format instructions.
856 *
857 * What we do here is:
858 *
859 * - Iterate through the list of format instructions, freeing any references
860 * to allocated memory in each instruction.
861 * - Free component references.
862 * - If requested, reset the component hash table; that will also free any
863 * references to components stored there.
864 *
865 */
866
867 void
868 fmt_free(struct format *fmt, int reset_comptable)
869 {
870 struct format *fp = fmt;
871
872 if (fp) {
873 while (! (fp->f_type == FT_DONE && fp->f_value == 0)) {
874 if (fp->f_flags & FF_STRALLOC)
875 free(fp->f_text);
876 if (fp->f_flags & FF_COMPREF)
877 free_component(fp->f_comp);
878 fp++;
879 }
880 free(fmt);
881 }
882
883 if (reset_comptable)
884 free_comptable();
885 }
886
887 /*
888 * Free just the text strings from all of the component hash table entries
889 */
890
891 void
892 fmt_freecomptext(void)
893 {
894 unsigned int i;
895 struct comp *cm;
896
897 for (i = 0; i < sizeof(wantcomp)/sizeof(wantcomp[0]); i++)
898 for (cm = wantcomp[i]; cm; cm = cm->c_next)
899 if (cm->c_text) {
900 free(cm->c_text);
901 cm->c_text = NULL;
902 }
903 }
904
905 /*
906 * Find a component in our hash table. This is just a public interface to
907 * the FINDCOMP macro, so we don't have to expose our hash table.
908 */
909
910 struct comp *
911 fmt_findcomp(char *component)
912 {
913 struct comp *cm;
914
915 FINDCOMP(cm, component);
916
917 return cm;
918 }
919
920 /*
921 * Like fmt_findcomp, but case-insensitive.
922 */
923
924 struct comp *
925 fmt_findcasecomp(char *component)
926 {
927 struct comp *cm;
928
929 for (cm = wantcomp[CHASH(component)]; cm; cm = cm->c_next)
930 if (strcasecmp(component, cm->c_name ? cm->c_name : "") == 0)
931 break;
932
933 return cm;
934 }
935
936 /*
937 * Add an entry to the component hash table
938 *
939 * Returns true if the component was added, 0 if it already existed.
940 *
941 */
942
943 int
944 fmt_addcompentry(char *component)
945 {
946 struct comp *cm;
947 int i;
948
949 FINDCOMP(cm, component);
950
951 if (cm)
952 return 0;
953
954 NEWCOMP(cm, component);
955
956 /*
957 * ncomp is really meant for fmt_compile() and this function is
958 * meant to be used outside of it. So decrement it just to be safe
959 * (internal callers should be using NEWCOMP()).
960 */
961
962 ncomp--;
963
964 return 1;
965 }
966
967 /*
968 * Add a string to a component hash table entry.
969 *
970 * Note the special handling for components marked with CT_ADDR. The comments
971 * in fmt_scan.h explain this in more detail.
972 */
973
974 int
975 fmt_addcomptext(char *component, char *text)
976 {
977 int i, found = 0, bucket = CHASH(component);
978 struct comp *cptr = wantcomp[bucket];
979 char *cp;
980
981 while (cptr) {
982 if (strcasecmp(component, cptr->c_name ? cptr->c_name : "") == 0) {
983 found++;
984 if (! cptr->c_text) {
985 cptr->c_text = getcpy(text);
986 } else {
987 i = strlen(cp = cptr->c_text) - 1;
988 if (cp[i] == '\n') {
989 if (cptr->c_type & CT_ADDR) {
990 cp[i] = '\0';
991 cp = add(",\n\t", cp);
992 } else {
993 cp = add("\t", cp);
994 }
995 }
996 cptr->c_text = add(text, cp);
997 }
998 }
999 cptr = cptr->c_next;
1000 }
1001
1002 return found ? bucket : -1;
1003 }
1004
1005 /*
1006 * Append text to a component we've already found. See notes in fmt_scan.h
1007 * for more information.
1008 */
1009
1010 void
1011 fmt_appendcomp(int bucket, char *component, char *text)
1012 {
1013 struct comp *cptr;
1014
1015 if (bucket != -1) {
1016 for (cptr = wantcomp[bucket]; cptr; cptr = cptr->c_next)
1017 if (strcasecmp(component, cptr->c_name ? cptr->c_name : "") == 0)
1018 cptr->c_text = add(text, cptr->c_text);
1019 }
1020 }
1021
1022 /*
1023 * Free and reset our component hash table
1024 */
1025
1026 static void
1027 free_comptable(void)
1028 {
1029 unsigned int i;
1030 struct comp *cm, *cm2;
1031
1032 for (i = 0; i < sizeof(wantcomp)/sizeof(wantcomp[0]); i++) {
1033 cm = wantcomp[i];
1034 while (cm != NULL) {
1035 cm2 = cm->c_next;
1036 free_component(cm);
1037 cm = cm2;
1038 }
1039 wantcomp[i] = 0;
1040 }
1041
1042 ncomp = 0;
1043 }
1044
1045 /*
1046 * Decrement the reference count of a component structure. If it reaches
1047 * zero, free it
1048 */
1049
1050 static void
1051 free_component(struct comp *cm)
1052 {
1053 if (--cm->c_refcount <= 0) {
1054 /* Shouldn't ever be NULL, but just in case ... */
1055 if (cm->c_name)
1056 free(cm->c_name);
1057 if (cm->c_text)
1058 free(cm->c_text);
1059 if (cm->c_type & CT_DATE)
1060 free(cm->c_tws);
1061 if (cm->c_type & CT_ADDR && cm->c_mn && cm->c_mn != &fmt_mnull)
1062 mnfree(cm->c_mn);
1063 free(cm);
1064 }
1065 }
1066
1067 /*
1068 * These functions handles the case of outputting terminal strings depending
1069 * on the terminfo setting.
1070 */
1071
1072 /*
1073 * We should only be called if we haven't yet called setupterm()
1074 */
1075
1076 void
1077 initialize_terminfo(void)
1078 {
1079 int errret, rc;
1080
1081 rc = setupterm(NULL, fileno(stdout), &errret);
1082
1083 if (rc != 0 || errret != 1)
1084 termstatus = -1;
1085 else
1086 termstatus = 1;
1087 }
1088
1089 /*
1090 * Place the results of the specified string entry into the str register.
1091 *
1092 * Arguments are:
1093 *
1094 * t - Pointer to instruction table entry (used to create fmt instruction)
1095 * cap - Name of terminfo capability to insert (e.g., "bold", or "sgr0").
1096 *
1097 * This ended up being more complicated than I hoped. You need to fetch the
1098 * entry via tigetstr(), but there MAY be a padding format embedded in what
1099 * gets returned by tigetstr(), so you have to run it through tputs().
1100 * And of course tputs() is designed to output to a terminal, so you have
1101 * capture every byte output by the tputs() callback to get the final
1102 * string to write to the format engine.
1103 *
1104 * If padding bytes are NULs that will be a problem for us, but some quick
1105 * experimentation suggests that padding bytes are mostly a non-issue anymore.
1106 * If they still crop up we'll have to figure out how to deal with them.
1107 */
1108
1109 void
1110 get_term_stringcap(struct ftable *t, char *cap)
1111 {
1112 char *parm;
1113
1114 /*
1115 * Common to all functions; initialize the termcap if we need it.
1116 * If it didn't initialize successfully, return silently
1117 */
1118
1119 if (termstatus == 0)
1120 initialize_terminfo();
1121
1122 termcbufp = termcbuf;
1123
1124 if (termstatus == -1)
1125 goto out;
1126
1127 parm = tigetstr(cap);
1128
1129 if (parm == (char *) -1 || parm == NULL) {
1130 goto out;
1131 }
1132
1133 tputs(parm, 1, termbytes);
1134
1135 out:
1136 termcbufp = '\0';
1137
1138 LS(t->f_type, termcbuf);
1139 }
1140
1141 /*
1142 * Store a sequence of characters in our local buffer
1143 */
1144
1145 static int
1146 termbytes(int c)
1147 {
1148 size_t offset;
1149
1150 /*
1151 * Bump up the buffer size if we've reached the end (leave room for
1152 * a trailing NUL)
1153 */
1154
1155 if ((offset = termcbufp - termcbuf) - 1 >= termcbufsz) {
1156 termcbufsz += 64;
1157 termcbuf = mh_xrealloc(termcbuf, termcbufsz);
1158 termcbufp = termcbuf + offset;
1159 }
1160
1161 *termcbufp++ = c;
1162
1163 return 0;
1164 }