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