1 /*
2  * zsh.h - standard header file
3  *
4  * This file is part of zsh, the Z shell.
5  *
6  * Copyright (c) 1992-1997 Paul Falstad
7  * All rights reserved.
8  *
9  * Permission is hereby granted, without written agreement and without
10  * license or royalty fees, to use, copy, modify, and distribute this
11  * software and to distribute modified versions of this software for any
12  * purpose, provided that the above copyright notice and the following
13  * two paragraphs appear in all copies of this software.
14  *
15  * In no event shall Paul Falstad or the Zsh Development Group be liable
16  * to any party for direct, indirect, special, incidental, or consequential
17  * damages arising out of the use of this software and its documentation,
18  * even if Paul Falstad and the Zsh Development Group have been advised of
19  * the possibility of such damage.
20  *
21  * Paul Falstad and the Zsh Development Group specifically disclaim any
22  * warranties, including, but not limited to, the implied warranties of
23  * merchantability and fitness for a particular purpose.  The software
24  * provided hereunder is on an "as is" basis, and Paul Falstad and the
25  * Zsh Development Group have no obligation to provide maintenance,
26  * support, updates, enhancements, or modifications.
27  *
28  */
29 
30 /* A few typical macros */
31 #define minimum(a,b)  ((a) < (b) ? (a) : (b))
32 
33 /*
34  * Our longest integer type:  will be a 64 bit either if long already is,
35  * or if we found some alternative such as long long.
36  */
37 #ifdef ZSH_64_BIT_TYPE
38 typedef ZSH_64_BIT_TYPE zlong;
39 #if defined(ZLONG_IS_LONG_LONG) && defined(LLONG_MAX)
40 #define ZLONG_MAX LLONG_MAX
41 #else
42 #ifdef ZLONG_IS_LONG_64
43 #define ZLONG_MAX LONG_MAX
44 #else
45 /* umm... */
46 #define  ZLONG_MAX ((zlong)9223372036854775807)
47 #endif
48 #endif
49 #ifdef ZSH_64_BIT_UTYPE
50 typedef ZSH_64_BIT_UTYPE zulong;
51 #else
52 typedef unsigned zlong zulong;
53 #endif
54 #else
55 typedef long zlong;
56 typedef unsigned long zulong;
57 #define ZLONG_MAX LONG_MAX
58 #endif
59 
60 /*
61  * Work out how to define large integer constants that will fit
62  * in a zlong.
63  */
64 #if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT)
65 /* We have some 64-bit type */
66 #ifdef LONG_IS_64_BIT
67 /* It's long */
68 #define ZLONG_CONST(x)  x ## l
69 #else
70 /* It's long long */
71 #ifdef ZLONG_IS_LONG_LONG
72 #define ZLONG_CONST(x)  x ## ll
73 #else
74 /*
75  * There's some 64-bit type, but we don't know what it is.
76  * We'll just cast it and hope the compiler does the right thing.
77  */
78 #define ZLONG_CONST(x) ((zlong)x)
79 #endif
80 #endif
81 #else
82 /* We're stuck with long */
83 #define ZLONG_CONST(x) (x ## l)
84 #endif
85 
86 /*
87  * Double float support requires 64-bit alignment, so if longs and
88  * pointers are less we need to pad out.
89  */
90 #ifndef LONG_IS_64_BIT
91 # define PAD_64_BIT 1
92 #endif
93 
94 /* math.c */
95 typedef struct {
96     union {
97 	zlong l;
98 	double d;
99     } u;
100     int type;
101 } mnumber;
102 
103 #define MN_INTEGER 1		/* mnumber is integer */
104 #define MN_FLOAT   2		/* mnumber is floating point */
105 #define MN_UNSET   4		/* mnumber not yet retrieved */
106 
107 typedef struct mathfunc *MathFunc;
108 typedef mnumber (*NumMathFunc)(char *, int, mnumber *, int);
109 typedef mnumber (*StrMathFunc)(char *, char *, int);
110 
111 struct mathfunc {
112     MathFunc next;
113     char *name;
114     int flags;			/* MFF_* flags defined below */
115     NumMathFunc nfunc;
116     StrMathFunc sfunc;
117     char *module;
118     int minargs;
119     int maxargs;
120     int funcid;
121 };
122 
123 /* Math function takes a string argument */
124 #define MFF_STR      1
125 /* Math function has been loaded from library */
126 #define MFF_ADDED    2
127 /* Math function is implemented by a shell function */
128 #define MFF_USERFUNC 4
129 /* When autoloading, enable all features in module */
130 #define MFF_AUTOALL  8
131 
132 
133 #define NUMMATHFUNC(name, func, min, max, id) \
134     { NULL, name, 0, func, NULL, NULL, min, max, id }
135 #define STRMATHFUNC(name, func, id) \
136     { NULL, name, MFF_STR, NULL, func, NULL, 0, 0, id }
137 
138 /* Character tokens are sometimes casted to (unsigned char)'s.         *
139  * Unfortunately, some compilers don't correctly cast signed to        *
140  * unsigned promotions; i.e. (int)(unsigned char)((char) -1) evaluates *
141  * to -1, instead of 255 like it should.  We circumvent the troubles   *
142  * of such shameful delinquency by casting to a larger unsigned type   *
143  * then back down to unsigned char.                                    */
144 
145 #ifdef BROKEN_SIGNED_TO_UNSIGNED_CASTING
146 # define STOUC(X)	((unsigned char)(unsigned short)(X))
147 #else
148 # define STOUC(X)	((unsigned char)(X))
149 #endif
150 
151 /* Meta together with the character following Meta denotes the character *
152  * which is the exclusive or of 32 and the character following Meta.     *
153  * This is used to represent characters which otherwise has special      *
154  * meaning for zsh.  These are the characters for which the imeta() test *
155  * is true: the null character, and the characters from Meta to Marker.  */
156 
157 #define Meta		((char) 0x83)
158 
159 /* Note that the fourth character in DEFAULT_IFS is Meta *
160  * followed by a space which denotes the null character. */
161 
162 #define DEFAULT_IFS	" \t\n\203 "
163 
164 /* As specified in the standard (POSIX 2008) */
165 
166 #define DEFAULT_IFS_SH	" \t\n"
167 
168 /*
169  * Character tokens.
170  * These should match the characters in ztokens, defined in lex.c
171  */
172 #define Pound		((char) 0x84)
173 #define String		((char) 0x85)
174 #define Hat		((char) 0x86)
175 #define Star		((char) 0x87)
176 #define Inpar		((char) 0x88)
177 #define Inparmath	((char) 0x89)
178 #define Outpar		((char) 0x8a)
179 #define Outparmath	((char) 0x8b)
180 #define Qstring	        ((char) 0x8c)
181 #define Equals		((char) 0x8d)
182 #define Bar	      	((char) 0x8e)
183 #define Inbrace	        ((char) 0x8f)
184 #define Outbrace	((char) 0x90)
185 #define Inbrack	        ((char) 0x91)
186 #define Outbrack	((char) 0x92)
187 #define Tick		((char) 0x93)
188 #define Inang		((char) 0x94)
189 #define Outang		((char) 0x95)
190 #define OutangProc	((char) 0x96)
191 #define Quest		((char) 0x97)
192 #define Tilde		((char) 0x98)
193 #define Qtick		((char) 0x99)
194 #define Comma		((char) 0x9a)
195 #define Dash            ((char) 0x9b) /* Only in patterns */
196 #define Bang            ((char) 0x9c) /* Only in patterns */
197 /*
198  * Marks the last of the group above.
199  * Remaining tokens are even more special.
200  */
201 #define LAST_NORMAL_TOK Bang
202 /*
203  * Null arguments: placeholders for single and double quotes
204  * and backslashes.
205  */
206 #define Snull		((char) 0x9d)
207 #define Dnull		((char) 0x9e)
208 #define Bnull		((char) 0x9f)
209 /*
210  * Backslash which will be returned to "\" instead of being stripped
211  * when we turn the string into a printable format.
212  */
213 #define Bnullkeep       ((char) 0xa0)
214 /*
215  * Null argument that does not correspond to any character.
216  * This should be last as it does not appear in ztokens and
217  * is used to initialise the IMETA type in inittyptab().
218  */
219 #define Nularg		((char) 0xa1)
220 
221 /*
222  * Take care to update the use of IMETA appropriately when adding
223  * tokens here.
224  */
225 /*
226  * Marker is used in the following special circumstances:
227  * - In paramsubst for rc_expand_param.
228  * - In pattern character arrays as guaranteed not to mark a character in
229  *   a string.
230  * - In assignments with the ASSPM_KEY_VALUE flag set in order to
231  *   mark that there is a key / value pair following.  If this
232  *   comes from [key]=value the Marker is followed by a null;
233  *   if from [key]+=value the Marker is followed by a '+' then a null.
234  * All the above are local uses --- any case where the Marker has
235  * escaped beyond the context in question is an error.
236  */
237 #define Marker		((char) 0xa2)
238 
239 /* chars that need to be quoted if meant literally */
240 
241 #define SPECCHARS "#$^*()=|{}[]`<>?~;&\n\t \\\'\""
242 
243 /* chars that need to be quoted for pattern matching */
244 
245 #define PATCHARS "#^*()|[]<>?~\\"
246 
247 /*
248  * Check for a possibly tokenized dash.
249  *
250  * A dash only needs to be a token in a character range, [a-z], but
251  * it's difficult in general to ensure that.  So it's turned into
252  * a token at the usual point in the lexer.  However, we need
253  * to check for a literal dash at many points.
254  */
255 #define IS_DASH(x) ((x) == '-' || (x) == Dash)
256 
257 /*
258  * Types of quote.  This is used in various places, so care needs
259  * to be taken when changing them.  (Oooh, don't you look surprised.)
260  * - Passed to quotestring() to indicate style.  This is the ultimate
261  *   destiny of most of the other uses of members of the enum.
262  * - In paramsubst(), to count q's in parameter substitution.
263  * - In the completion code, where we maintain a stack of quotation types.
264  */
265 enum {
266     /*
267      * No quote.  Not a valid quote, but useful in the substitution
268      * and completion code to indicate we're not doing any quoting.
269      */
270     QT_NONE,
271     /* Backslash: \ */
272     QT_BACKSLASH,
273     /* Single quote: ' */
274     QT_SINGLE,
275     /* Double quote: " */
276     QT_DOUBLE,
277     /* Print-style quote: $' */
278     QT_DOLLARS,
279     /*
280      * Backtick: `
281      * Not understood by many parts of the code; here for a convenience
282      * in those cases where we need to represent a complete set.
283      */
284     QT_BACKTICK,
285     /*
286      * Single quotes, but the default is not to quote unless necessary.
287      * This is only useful as an argument to quotestring().
288      */
289     QT_SINGLE_OPTIONAL,
290     /*
291      * Only quote pattern characters.
292      * ${(b)foo} guarantees that ${~foo} matches the string
293      * contained in foo.
294      */
295     QT_BACKSLASH_PATTERN,
296     /*
297      * As QT_BACKSLASH, but a NULL string is shown as ''.
298      */
299     QT_BACKSLASH_SHOWNULL,
300     /*
301      * Quoting as produced by quotedzputs(), used for human
302      * readability of parameter values.
303      */
304     QT_QUOTEDZPUTS
305 };
306 
307 #define QT_IS_SINGLE(x)	((x) == QT_SINGLE || (x) == QT_SINGLE_OPTIONAL)
308 
309 /*
310  * Lexical tokens: unlike the character tokens above, these never
311  * appear in strings and don't necessarily represent a single character.
312  */
313 
314 enum lextok {
315     NULLTOK,		/* 0  */
316     SEPER,
317     NEWLIN,
318     SEMI,
319     DSEMI,
320     AMPER,		/* 5  */
321     INPAR,
322     OUTPAR,
323     DBAR,
324     DAMPER,
325     OUTANG,		/* 10 */
326     OUTANGBANG,
327     DOUTANG,
328     DOUTANGBANG,
329     INANG,
330     INOUTANG,		/* 15 */
331     DINANG,
332     DINANGDASH,
333     INANGAMP,
334     OUTANGAMP,
335     AMPOUTANG,		/* 20 */
336     OUTANGAMPBANG,
337     DOUTANGAMP,
338     DOUTANGAMPBANG,
339     TRINANG,
340     BAR,		/* 25 */
341     BARAMP,
342     INOUTPAR,
343     DINPAR,
344     DOUTPAR,
345     AMPERBANG,		/* 30 */
346     SEMIAMP,
347     SEMIBAR,
348     DOUTBRACK,
349     STRING,
350     ENVSTRING,		/* 35 */
351     ENVARRAY,
352     ENDINPUT,
353     LEXERR,
354 
355     /* Tokens for reserved words */
356     BANG,	/* !         */
357     DINBRACK,	/* [[        */	/* 40 */
358     INBRACE,    /* {         */
359     OUTBRACE,   /* }         */
360     CASE,	/* case      */
361     COPROC,	/* coproc    */
362     DOLOOP,	/* do        */ /* 45 */
363     DONE,	/* done      */
364     ELIF,	/* elif      */
365     ELSE,	/* else      */
366     ZEND,	/* end       */
367     ESAC,	/* esac      */ /* 50 */
368     FI,		/* fi        */
369     FOR,	/* for       */
370     FOREACH,	/* foreach   */
371     FUNC,	/* function  */
372     IF,		/* if        */ /* 55 */
373     NOCORRECT,	/* nocorrect */
374     REPEAT,	/* repeat    */
375     SELECT,	/* select    */
376     THEN,	/* then      */
377     TIME,	/* time      */ /* 60 */
378     UNTIL,	/* until     */
379     WHILE,	/* while     */
380     TYPESET     /* typeset or similar */
381 };
382 
383 /* Redirection types.  If you modify this, you may also have to modify *
384  * redirtab in parse.c and getredirs() in text.c and the IS_* macros   *
385  * below.                                                              */
386 
387 enum {
388     REDIR_WRITE,		/* > */
389     REDIR_WRITENOW,		/* >| */
390     REDIR_APP,		/* >> */
391     REDIR_APPNOW,		/* >>| */
392     REDIR_ERRWRITE,		/* &>, >& */
393     REDIR_ERRWRITENOW,	/* >&| */
394     REDIR_ERRAPP,		/* >>& */
395     REDIR_ERRAPPNOW,		/* >>&| */
396     REDIR_READWRITE,		/* <> */
397     REDIR_READ,		/* < */
398     REDIR_HEREDOC,		/* << */
399     REDIR_HEREDOCDASH,	/* <<- */
400     REDIR_HERESTR,		/* <<< */
401     REDIR_MERGEIN,		/* <&n */
402     REDIR_MERGEOUT,		/* >&n */
403     REDIR_CLOSE,		/* >&-, <&- */
404     REDIR_INPIPE,		/* < <(...) */
405     REDIR_OUTPIPE		/* > >(...) */
406 };
407 #define REDIR_TYPE_MASK	(0x1f)
408 /* Redir using {var} syntax */
409 #define REDIR_VARID_MASK (0x20)
410 /* Mark here-string that came from a here-document */
411 #define REDIR_FROM_HEREDOC_MASK (0x40)
412 
413 #define IS_WRITE_FILE(X)      ((X)>=REDIR_WRITE && (X)<=REDIR_READWRITE)
414 #define IS_APPEND_REDIR(X)    (IS_WRITE_FILE(X) && ((X) & 2))
415 #define IS_CLOBBER_REDIR(X)   (IS_WRITE_FILE(X) && ((X) & 1))
416 #define IS_ERROR_REDIR(X)     ((X)>=REDIR_ERRWRITE && (X)<=REDIR_ERRAPPNOW)
417 #define IS_READFD(X)          (((X)>=REDIR_READWRITE && (X)<=REDIR_MERGEIN) || (X)==REDIR_INPIPE)
418 #define IS_REDIROP(X)         ((X)>=OUTANG && (X)<=TRINANG)
419 
420 /*
421  * Values for the fdtable array.  They say under what circumstances
422  * the fd will be close.  The fdtable is an unsigned char, so these are
423  * #define's rather than an enum.
424  */
425 /* Entry not used. */
426 #define FDT_UNUSED		0
427 /*
428  * Entry used internally by the shell, should not be visible to other
429  * processes.
430  */
431 #define FDT_INTERNAL		1
432 /*
433  * Entry visible to other processes, for example created using
434  * the {varid}> file syntax.
435  */
436 #define FDT_EXTERNAL		2
437 /*
438  * Entry visible to other processes but controlled by a module.
439  * The difference from FDT_EXTERNAL is that closing this using
440  * standard fd syntax will fail as there is some tidying up that
441  * needs to be done by the module's own mechanism.
442  */
443 #define FDT_MODULE		3
444 /*
445  * Entry used by output from the XTRACE option.
446  */
447 #define FDT_XTRACE		4
448 /*
449  * Entry used for file locking.
450  */
451 #define FDT_FLOCK		5
452 /*
453  * As above, but the fd is not marked for closing on exec,
454  * so the shell can still exec the last process.
455  */
456 #define FDT_FLOCK_EXEC		6
457 /*
458  * Entry used by a process substitution.
459  * This marker is not tested internally as we associated the file
460  * descriptor with a job for closing.
461  *
462  * This is not used unless PATH_DEV_FD is defined.
463  */
464 #define FDT_PROC_SUBST		7
465 /*
466  * Mask to get the basic FDT type.
467  */
468 #define FDT_TYPE_MASK		15
469 
470 /*
471  * Bit flag that fd is saved for later restoration.
472  * Currently this is only use with FDT_INTERNAL.  We use this fact so as
473  * not to have to mask checks against other types.
474  */
475 #define FDT_SAVED_MASK		16
476 
477 /* Flags for input stack */
478 #define INP_FREE      (1<<0)	/* current buffer can be free'd            */
479 #define INP_ALIAS     (1<<1)	/* expanding alias or history              */
480 #define INP_HIST      (1<<2)	/* expanding history                       */
481 #define INP_CONT      (1<<3)	/* continue onto previously stacked input  */
482 #define INP_ALCONT    (1<<4)	/* stack is continued from alias expn.     */
483 #define INP_HISTCONT  (1<<5)	/* stack is continued from history expn.   */
484 #define INP_LINENO    (1<<6)    /* update line number                      */
485 #define INP_APPEND    (1<<7)    /* Append new lines to allow backup        */
486 #define INP_RAW_KEEP  (1<<8)    /* Input needed in raw mode even if alias  */
487 
488 /* Flags for metafy */
489 #define META_REALLOC	0
490 #define META_USEHEAP	1
491 #define META_STATIC	2
492 #define META_DUP	3
493 #define META_ALLOC	4
494 #define META_NOALLOC	5
495 #define META_HEAPDUP	6
496 #define META_HREALLOC	7
497 
498 /* Context to save and restore (bit fields) */
499 enum {
500     /* History mechanism */
501     ZCONTEXT_HIST       = (1<<0),
502     /* Lexical analyser */
503     ZCONTEXT_LEX        = (1<<1),
504     /* Parser */
505     ZCONTEXT_PARSE      = (1<<2)
506 };
507 
508 /* Report from entersubsh() to pass subshell info to addproc */
509 struct entersubsh_ret {
510     /* Process group leader chosen by subshell, else -1 */
511     int gleader;
512     /* list_pipe_job setting used by subshell, else -1 */
513     int list_pipe_job;
514 };
515 
516 /**************************/
517 /* Abstract types for zsh */
518 /**************************/
519 
520 typedef struct alias     *Alias;
521 typedef struct asgment   *Asgment;
522 typedef struct builtin   *Builtin;
523 typedef struct cmdnam    *Cmdnam;
524 typedef struct complist  *Complist;
525 typedef struct conddef   *Conddef;
526 typedef struct dirsav    *Dirsav;
527 typedef struct emulation_options *Emulation_options;
528 typedef struct execcmd_params *Execcmd_params;
529 typedef struct features  *Features;
530 typedef struct feature_enables  *Feature_enables;
531 typedef struct funcstack *Funcstack;
532 typedef struct funcwrap  *FuncWrap;
533 typedef struct hashnode  *HashNode;
534 typedef struct hashtable *HashTable;
535 typedef struct heap      *Heap;
536 typedef struct heapstack *Heapstack;
537 typedef struct histent   *Histent;
538 typedef struct hookdef   *Hookdef;
539 typedef struct imatchdata *Imatchdata;
540 typedef struct jobfile   *Jobfile;
541 typedef struct job       *Job;
542 typedef struct linkedmod *Linkedmod;
543 typedef struct linknode  *LinkNode;
544 typedef union  linkroot  *LinkList;
545 typedef struct module    *Module;
546 typedef struct nameddir  *Nameddir;
547 typedef struct options	 *Options;
548 typedef struct optname   *Optname;
549 typedef struct param     *Param;
550 typedef struct paramdef  *Paramdef;
551 typedef struct patstralloc  *Patstralloc;
552 typedef struct patprog   *Patprog;
553 typedef struct prepromptfn *Prepromptfn;
554 typedef struct process   *Process;
555 typedef struct redir     *Redir;
556 typedef struct reswd     *Reswd;
557 typedef struct shfunc    *Shfunc;
558 typedef struct timedfn   *Timedfn;
559 typedef struct value     *Value;
560 
561 /********************************/
562 /* Definitions for linked lists */
563 /********************************/
564 
565 /* linked list abstract data type */
566 
567 struct linknode {
568     LinkNode next;
569     LinkNode prev;
570     void *dat;
571 };
572 
573 struct linklist {
574     LinkNode first;
575     LinkNode last;
576     int flags;
577 };
578 
579 union linkroot {
580     struct linklist list;
581     struct linknode node;
582 };
583 
584 /* Macros for manipulating link lists */
585 
586 #define firstnode(X)        ((X)->list.first)
587 #define lastnode(X)         ((X)->list.last)
588 #define peekfirst(X)        (firstnode(X)->dat)
589 #define peeklast(X)         (lastnode(X)->dat)
590 #define addlinknode(X,Y)    insertlinknode(X,lastnode(X),Y)
591 #define zaddlinknode(X,Y)   zinsertlinknode(X,lastnode(X),Y)
592 #define uaddlinknode(X,Y)   uinsertlinknode(X,lastnode(X),Y)
593 #define empty(X)            (firstnode(X) == NULL)
594 #define nonempty(X)         (firstnode(X) != NULL)
595 #define getaddrdata(X)      (&((X)->dat))
596 #define getdata(X)          ((X)->dat)
597 #define setdata(X,Y)        ((X)->dat = (Y))
598 #define nextnode(X)         ((X)->next)
599 #define prevnode(X)         ((X)->prev)
600 #define pushnode(X,Y)       insertlinknode(X,&(X)->node,Y)
601 #define zpushnode(X,Y)      zinsertlinknode(X,&(X)->node,Y)
602 #define incnode(X)          (X = nextnode(X))
603 #define decnode(X)          (X = prevnode(X))
604 #define firsthist()         (hist_ring? hist_ring->down->histnum : curhist)
605 #define setsizednode(X,Y,Z) (firstnode(X)[(Y)].dat = (void *) (Z))
606 
607 /* stack allocated linked lists */
608 
609 #define local_list0(N) union linkroot N
610 #define init_list0(N) \
611     do { \
612         (N).list.first = NULL; \
613         (N).list.last = &(N).node; \
614         (N).list.flags = 0; \
615     } while (0)
616 #define local_list1(N) union linkroot N; struct linknode __n0
617 #define init_list1(N,V0) \
618     do { \
619         (N).list.first = &__n0; \
620         (N).list.last = &__n0; \
621         (N).list.flags = 0; \
622         __n0.next = NULL; \
623         __n0.prev = &(N).node; \
624         __n0.dat = (void *) (V0); \
625     } while (0)
626 
627 /*************************************/
628 /* Specific elements of linked lists */
629 /*************************************/
630 
631 typedef void (*voidvoidfnptr_t) _((void));
632 
633 /*
634  * Element of the prepromptfns list.
635  */
636 struct prepromptfn {
637     voidvoidfnptr_t func;
638 };
639 
640 
641 /*
642  * Element of the timedfns list.
643  */
644 struct timedfn {
645     voidvoidfnptr_t func;
646     time_t when;
647 };
648 
649 /********************************/
650 /* Definitions for syntax trees */
651 /********************************/
652 
653 /* These are control flags that are passed *
654  * down the execution pipeline.            */
655 #define Z_TIMED	 (1<<0)	/* pipeline is being timed                   */
656 #define Z_SYNC	 (1<<1)	/* run this sublist synchronously       (;)  */
657 #define Z_ASYNC  (1<<2)	/* run this sublist asynchronously      (&)  */
658 #define Z_DISOWN (1<<3)	/* run this sublist without job control (&|) */
659 /* (1<<4) is used for Z_END, see the wordcode definitions */
660 /* (1<<5) is used for Z_SIMPLE, see the wordcode definitions */
661 
662 /*
663  * Condition types.
664  *
665  * Careful when changing these: both cond_binary_ops in text.c and
666  * condstr in cond.c depend on these.  (The zsh motto is "two instances
667  * are better than one".  Or something.)
668  */
669 
670 #define COND_NOT    0
671 #define COND_AND    1
672 #define COND_OR     2
673 #define COND_STREQ  3
674 #define COND_STRDEQ 4
675 #define COND_STRNEQ 5
676 #define COND_STRLT  6
677 #define COND_STRGTR 7
678 #define COND_NT     8
679 #define COND_OT     9
680 #define COND_EF    10
681 #define COND_EQ    11
682 #define COND_NE    12
683 #define COND_LT    13
684 #define COND_GT    14
685 #define COND_LE    15
686 #define COND_GE    16
687 #define COND_REGEX 17
688 #define COND_MOD   18
689 #define COND_MODI  19
690 
691 typedef int (*CondHandler) _((char **, int));
692 
693 struct conddef {
694     Conddef next;		/* next in list                       */
695     char *name;			/* the condition name                 */
696     int flags;			/* see CONDF_* below                  */
697     CondHandler handler;	/* handler function                   */
698     int min;			/* minimum number of strings          */
699     int max;			/* maximum number of strings          */
700     int condid;			/* for overloading handler functions  */
701     char *module;		/* module to autoload                 */
702 };
703 
704 /* Condition is an infix */
705 #define CONDF_INFIX   1
706 /* Condition has been loaded from library */
707 #define CONDF_ADDED   2
708 /* When autoloading, enable all features in library */
709 #define CONDF_AUTOALL 4
710 
711 #define CONDDEF(name, flags, handler, min, max, condid) \
712     { NULL, name, flags, handler, min, max, condid, NULL }
713 
714 /* Flags for redirections */
715 
716 enum {
717     /* Mark a here-string that came from a here-document */
718     REDIRF_FROM_HEREDOC = 1
719 };
720 
721 /* tree element for redirection lists */
722 
723 struct redir {
724     int type;
725     int flags;
726     int fd1, fd2;
727     char *name;
728     char *varid;
729     char *here_terminator;
730     char *munged_here_terminator;
731 };
732 
733 /* The number of fds space is allocated for  *
734  * each time a multio must increase in size. */
735 #define MULTIOUNIT 8
736 
737 /* A multio is a list of fds associated with a certain fd.       *
738  * Thus if you do "foo >bar >ble", the multio for fd 1 will have *
739  * two fds, the result of open("bar",...), and the result of     *
740  * open("ble",....).                                             */
741 
742 /* structure used for multiple i/o redirection */
743 /* one for each fd open                        */
744 
745 struct multio {
746     int ct;			/* # of redirections on this fd                 */
747     int rflag;			/* 0 if open for reading, 1 if open for writing */
748     int pipe;			/* fd of pipe if ct > 1                         */
749     int fds[MULTIOUNIT];	/* list of src/dests redirected to/from this fd */
750 };
751 
752 /* lvalue for variable assignment/expansion */
753 
754 struct value {
755     int isarr;
756     Param pm;		/* parameter node                      */
757     int flags;		/* flags defined below                 */
758     int start;		/* first element of array slice, or -1 */
759     int end;		/* 1-rel last element of array slice, or -1 */
760     char **arr;		/* cache for hash turned into array */
761 };
762 
763 enum {
764     VALFLAG_INV =	0x0001,	/* We are performing inverse subscripting */
765     VALFLAG_EMPTY =	0x0002,	/* Subscripted range is empty */
766     VALFLAG_SUBST =     0x0004  /* Substitution, so apply padding, case flags */
767 };
768 
769 #define MAX_ARRLEN    262144
770 
771 /********************************************/
772 /* Definitions for word code                 */
773 /********************************************/
774 
775 typedef unsigned int wordcode;
776 typedef wordcode *Wordcode;
777 
778 typedef struct funcdump *FuncDump;
779 typedef struct eprog *Eprog;
780 
781 struct funcdump {
782     FuncDump next;		/* next in list */
783     dev_t dev;			/* device */
784     ino_t ino;			/* indoe number */
785     int fd;			/* file descriptor */
786     Wordcode map;		/* pointer to header */
787     Wordcode addr;		/* mapped region */
788     int len;			/* length */
789     int count;			/* reference count */
790     char *filename;
791 };
792 
793 /*
794  * A note on the use of reference counts in Eprogs.
795  *
796  * When an Eprog is created, nref is set to -1 if the Eprog is on the
797  * heap; then no attempt is ever made to free it.  (This information is
798  * already present in EF_HEAP; we use the redundancy for debugging
799  * checks.)
800  *
801  * Otherwise, nref is initialised to 1.  Calling freeprog() decrements
802  * nref and frees the Eprog if the count is now zero.  When the Eprog
803  * is in use, we call useeprog() at the start and freeprog() at the
804  * end to increment and decrement the reference counts.  If an attempt
805  * is made to free the Eprog from within, this will then take place
806  * when execution is finished, typically in the call to freeeprog()
807  * in execode().  If the Eprog was on the heap, neither useeprog()
808  * nor freeeprog() has any effect.
809  */
810 struct eprog {
811     int flags;			/* EF_* below */
812     int len;			/* total block length */
813     int npats;			/* Patprog cache size */
814     int nref;			/* number of references: delete when zero */
815     Patprog *pats;		/* the memory block, the patterns */
816     Wordcode prog;		/* memory block ctd, the code */
817     char *strs;			/* memory block ctd, the strings */
818     Shfunc shf;			/* shell function for autoload */
819     FuncDump dump;		/* dump file this is in */
820 };
821 
822 #define EF_REAL 1
823 #define EF_HEAP 2
824 #define EF_MAP  4
825 #define EF_RUN  8
826 
827 typedef struct estate *Estate;
828 
829 struct estate {
830     Eprog prog;			/* the eprog executed */
831     Wordcode pc;		/* program counter, current pos */
832     char *strs;			/* strings from prog */
833 };
834 
835 typedef struct eccstr *Eccstr;
836 
837 struct eccstr {
838     Eccstr left, right;
839     char *str;
840     wordcode offs, aoffs;
841     int nfunc;
842     int hashval;
843 };
844 
845 #define EC_NODUP  0
846 #define EC_DUP    1
847 #define EC_DUPTOK 2
848 
849 #define WC_CODEBITS 5
850 
851 #define wc_code(C)   ((C) & ((wordcode) ((1 << WC_CODEBITS) - 1)))
852 #define wc_data(C)   ((C) >> WC_CODEBITS)
853 #define wc_bdata(D)  ((D) << WC_CODEBITS)
854 #define wc_bld(C,D)  (((wordcode) (C)) | (((wordcode) (D)) << WC_CODEBITS))
855 
856 #define WC_END      0
857 #define WC_LIST     1
858 #define WC_SUBLIST  2
859 #define WC_PIPE     3
860 #define WC_REDIR    4
861 #define WC_ASSIGN   5
862 #define WC_SIMPLE   6
863 #define WC_TYPESET  7
864 #define WC_SUBSH    8
865 #define WC_CURSH    9
866 #define WC_TIMED   10
867 #define WC_FUNCDEF 11
868 #define WC_FOR     12
869 #define WC_SELECT  13
870 #define WC_WHILE   14
871 #define WC_REPEAT  15
872 #define WC_CASE    16
873 #define WC_IF      17
874 #define WC_COND    18
875 #define WC_ARITH   19
876 #define WC_AUTOFN  20
877 #define WC_TRY     21
878 
879 /* increment as necessary */
880 #define WC_COUNT   22
881 
882 #define WCB_END()           wc_bld(WC_END, 0)
883 
884 #define WC_LIST_TYPE(C)     wc_data(C)
885 #define Z_END               (1<<4)
886 #define Z_SIMPLE            (1<<5)
887 #define WC_LIST_FREE        (6)	/* Next bit available in integer */
888 #define WC_LIST_SKIP(C)     (wc_data(C) >> WC_LIST_FREE)
889 #define WCB_LIST(T,O)       wc_bld(WC_LIST, ((T) | ((O) << WC_LIST_FREE)))
890 
891 #define WC_SUBLIST_TYPE(C)  (wc_data(C) & ((wordcode) 3))
892 #define WC_SUBLIST_END      0
893 #define WC_SUBLIST_AND      1
894 #define WC_SUBLIST_OR       2
895 #define WC_SUBLIST_FLAGS(C) (wc_data(C) & ((wordcode) 0x1c))
896 #define WC_SUBLIST_COPROC   4
897 #define WC_SUBLIST_NOT      8
898 #define WC_SUBLIST_SIMPLE  16
899 #define WC_SUBLIST_FREE    (5)	/* Next bit available in integer */
900 #define WC_SUBLIST_SKIP(C)  (wc_data(C) >> WC_SUBLIST_FREE)
901 #define WCB_SUBLIST(T,F,O)  wc_bld(WC_SUBLIST, \
902 				   ((T) | (F) | ((O) << WC_SUBLIST_FREE)))
903 
904 #define WC_PIPE_TYPE(C)     (wc_data(C) & ((wordcode) 1))
905 #define WC_PIPE_END         0
906 #define WC_PIPE_MID         1
907 #define WC_PIPE_LINENO(C)   (wc_data(C) >> 1)
908 #define WCB_PIPE(T,L)       wc_bld(WC_PIPE, ((T) | ((L) << 1)))
909 
910 #define WC_REDIR_TYPE(C)    ((int)(wc_data(C) & REDIR_TYPE_MASK))
911 #define WC_REDIR_VARID(C)   ((int)(wc_data(C) & REDIR_VARID_MASK))
912 #define WC_REDIR_FROM_HEREDOC(C) ((int)(wc_data(C) & REDIR_FROM_HEREDOC_MASK))
913 #define WCB_REDIR(T)        wc_bld(WC_REDIR, (T))
914 /* Size of redir is 4 words if REDIR_VARID_MASK is set, else 3 */
915 #define WC_REDIR_WORDS(C)			\
916     ((WC_REDIR_VARID(C) ? 4 : 3) +		\
917      (WC_REDIR_FROM_HEREDOC(C) ? 2 : 0))
918 
919 #define WC_ASSIGN_TYPE(C)   (wc_data(C) & ((wordcode) 1))
920 #define WC_ASSIGN_TYPE2(C)  ((wc_data(C) & ((wordcode) 2)) >> 1)
921 #define WC_ASSIGN_SCALAR    0
922 #define WC_ASSIGN_ARRAY     1
923 #define WC_ASSIGN_NEW       0
924 /*
925  * In normal assignment, this indicate += to append.
926  * In assignment following a typeset, where that's not allowed,
927  * we overload this to indicate a variable without an
928  * assignment.
929  */
930 #define WC_ASSIGN_INC       1
931 #define WC_ASSIGN_NUM(C)    (wc_data(C) >> 2)
932 #define WCB_ASSIGN(T,A,N)   wc_bld(WC_ASSIGN, ((T) | ((A) << 1) | ((N) << 2)))
933 
934 #define WC_SIMPLE_ARGC(C)   wc_data(C)
935 #define WCB_SIMPLE(N)       wc_bld(WC_SIMPLE, (N))
936 
937 #define WC_TYPESET_ARGC(C)  wc_data(C)
938 #define WCB_TYPESET(N)      wc_bld(WC_TYPESET, (N))
939 
940 #define WC_SUBSH_SKIP(C)    wc_data(C)
941 #define WCB_SUBSH(O)        wc_bld(WC_SUBSH, (O))
942 
943 #define WC_CURSH_SKIP(C)    wc_data(C)
944 #define WCB_CURSH(O)        wc_bld(WC_CURSH, (O))
945 
946 #define WC_TIMED_TYPE(C)    wc_data(C)
947 #define WC_TIMED_EMPTY      0
948 #define WC_TIMED_PIPE       1
949 #define WCB_TIMED(T)        wc_bld(WC_TIMED, (T))
950 
951 #define WC_FUNCDEF_SKIP(C)  wc_data(C)
952 #define WCB_FUNCDEF(O)      wc_bld(WC_FUNCDEF, (O))
953 
954 #define WC_FOR_TYPE(C)      (wc_data(C) & 3)
955 #define WC_FOR_PPARAM       0
956 #define WC_FOR_LIST         1
957 #define WC_FOR_COND         2
958 #define WC_FOR_SKIP(C)      (wc_data(C) >> 2)
959 #define WCB_FOR(T,O)        wc_bld(WC_FOR, ((T) | ((O) << 2)))
960 
961 #define WC_SELECT_TYPE(C)   (wc_data(C) & 1)
962 #define WC_SELECT_PPARAM    0
963 #define WC_SELECT_LIST      1
964 #define WC_SELECT_SKIP(C)   (wc_data(C) >> 1)
965 #define WCB_SELECT(T,O)     wc_bld(WC_SELECT, ((T) | ((O) << 1)))
966 
967 #define WC_WHILE_TYPE(C)    (wc_data(C) & 1)
968 #define WC_WHILE_WHILE      0
969 #define WC_WHILE_UNTIL      1
970 #define WC_WHILE_SKIP(C)    (wc_data(C) >> 1)
971 #define WCB_WHILE(T,O)      wc_bld(WC_WHILE, ((T) | ((O) << 1)))
972 
973 #define WC_REPEAT_SKIP(C)   wc_data(C)
974 #define WCB_REPEAT(O)       wc_bld(WC_REPEAT, (O))
975 
976 #define WC_TRY_SKIP(C)	    wc_data(C)
977 #define WCB_TRY(O)	    wc_bld(WC_TRY, (O))
978 
979 #define WC_CASE_TYPE(C)     (wc_data(C) & 7)
980 #define WC_CASE_HEAD        0
981 #define WC_CASE_OR          1
982 #define WC_CASE_AND         2
983 #define WC_CASE_TESTAND     3
984 #define WC_CASE_FREE	    (3) /* Next bit available in integer */
985 #define WC_CASE_SKIP(C)     (wc_data(C) >> WC_CASE_FREE)
986 #define WCB_CASE(T,O)       wc_bld(WC_CASE, ((T) | ((O) << WC_CASE_FREE)))
987 
988 #define WC_IF_TYPE(C)       (wc_data(C) & 3)
989 #define WC_IF_HEAD          0
990 #define WC_IF_IF            1
991 #define WC_IF_ELIF          2
992 #define WC_IF_ELSE          3
993 #define WC_IF_SKIP(C)       (wc_data(C) >> 2)
994 #define WCB_IF(T,O)         wc_bld(WC_IF, ((T) | ((O) << 2)))
995 
996 #define WC_COND_TYPE(C)     (wc_data(C) & 127)
997 #define WC_COND_SKIP(C)     (wc_data(C) >> 7)
998 #define WCB_COND(T,O)       wc_bld(WC_COND, ((T) | ((O) << 7)))
999 
1000 #define WCB_ARITH()         wc_bld(WC_ARITH, 0)
1001 
1002 #define WCB_AUTOFN()        wc_bld(WC_AUTOFN, 0)
1003 
1004 /********************************************/
1005 /* Definitions for job table and job control */
1006 /********************************************/
1007 
1008 /* Entry in filelist linked list in job table */
1009 
1010 struct jobfile {
1011     /* Record to be deleted or closed */
1012     union {
1013 	char *name; /* Name of file to delete */
1014 	int fd;	    /* File descriptor to close */
1015     } u;
1016     /* Discriminant */
1017     int is_fd;
1018 };
1019 
1020 /* entry in the job table */
1021 
1022 struct job {
1023     pid_t gleader;		/* process group leader of this job  */
1024     pid_t other;		/* subjob id (SUPERJOB)
1025 				 * or subshell pid (SUBJOB) */
1026     int stat;                   /* see STATs below                   */
1027     char *pwd;			/* current working dir of shell when *
1028 				 * this job was spawned              */
1029     struct process *procs;	/* list of processes                 */
1030     struct process *auxprocs;	/* auxiliary processes e.g multios   */
1031     LinkList filelist;		/* list of files to delete when done */
1032 				/* elements are struct jobfile */
1033     int stty_in_env;		/* if STTY=... is present            */
1034     struct ttyinfo *ty;		/* the modes specified by STTY       */
1035 };
1036 
1037 #define STAT_CHANGED	(0x0001) /* status changed and not reported      */
1038 #define STAT_STOPPED	(0x0002) /* all procs stopped or exited          */
1039 #define STAT_TIMED	(0x0004) /* job is being timed                   */
1040 #define STAT_DONE	(0x0008) /* job is done                          */
1041 #define STAT_LOCKED	(0x0010) /* shell is finished creating this job, */
1042                                  /*   may be deleted from job table      */
1043 #define STAT_NOPRINT	(0x0020) /* job was killed internally,           */
1044                                  /*   we don't want to show that         */
1045 #define STAT_INUSE	(0x0040) /* this job entry is in use             */
1046 #define STAT_SUPERJOB	(0x0080) /* job has a subjob                     */
1047 #define STAT_SUBJOB	(0x0100) /* job is a subjob                      */
1048 #define STAT_WASSUPER   (0x0200) /* was a super-job, sub-job needs to be */
1049 				 /* deleted */
1050 #define STAT_CURSH	(0x0400) /* last command is in current shell     */
1051 #define STAT_NOSTTY	(0x0800) /* the tty settings are not inherited   */
1052 				 /* from this job when it exits.         */
1053 #define STAT_ATTACH	(0x1000) /* delay reattaching shell to tty       */
1054 #define STAT_SUBLEADER  (0x2000) /* is super-job, but leader is sub-shell */
1055 
1056 #define STAT_BUILTIN    (0x4000) /* job at tail of pipeline is a builtin */
1057 #define STAT_SUBJOB_ORPHANED (0x8000)
1058                                  /* STAT_SUBJOB with STAT_SUPERJOB exited */
1059 #define STAT_DISOWN     (0x10000) /* STAT_SUPERJOB with disown pending */
1060 
1061 #define SP_RUNNING -1		/* fake status for jobs currently running */
1062 
1063 struct timeinfo {
1064     long ut;                    /* user space time   */
1065     long st;                    /* system space time */
1066 };
1067 
1068 #define JOBTEXTSIZE 80
1069 
1070 /* Size to initialise the job table to, and to increment it by when needed. */
1071 #define MAXJOBS_ALLOC	(50)
1072 
1073 /* node in job process lists */
1074 
1075 #ifdef HAVE_GETRUSAGE
1076 typedef struct rusage child_times_t;
1077 #else
1078 typedef struct timeinfo child_times_t;
1079 #endif
1080 
1081 struct process {
1082     struct process *next;
1083     pid_t pid;                  /* process id                       */
1084     char text[JOBTEXTSIZE];	/* text to print when 'jobs' is run */
1085     int status;			/* return code from waitpid/wait3() */
1086     child_times_t ti;
1087     struct timeval bgtime;	/* time job was spawned             */
1088     struct timeval endtime;	/* time job exited                  */
1089 };
1090 
1091 struct execstack {
1092     struct execstack *next;
1093 
1094     pid_t list_pipe_pid;
1095     int nowait;
1096     int pline_level;
1097     int list_pipe_child;
1098     int list_pipe_job;
1099     char list_pipe_text[JOBTEXTSIZE];
1100     int lastval;
1101     int noeval;
1102     int badcshglob;
1103     pid_t cmdoutpid;
1104     int cmdoutval;
1105     int use_cmdoutval;
1106     pid_t procsubstpid;
1107     int trap_return;
1108     int trap_state;
1109     int trapisfunc;
1110     int traplocallevel;
1111     int noerrs;
1112     int this_noerrexit;
1113     char *underscore;
1114 };
1115 
1116 struct heredocs {
1117     struct heredocs *next;
1118     int type;
1119     int pc;
1120     char *str;
1121 };
1122 
1123 struct dirsav {
1124     int dirfd, level;
1125     char *dirname;
1126     dev_t dev;
1127     ino_t ino;
1128 };
1129 
1130 #define MAX_PIPESTATS 256
1131 
1132 /*******************************/
1133 /* Definitions for Hash Tables */
1134 /*******************************/
1135 
1136 typedef void *(*VFunc) _((void *));
1137 typedef void (*FreeFunc) _((void *));
1138 
1139 typedef unsigned (*HashFunc)       _((const char *));
1140 typedef void     (*TableFunc)      _((HashTable));
1141 /*
1142  * Note that this is deliberately "char *", not "const char *",
1143  * since the AddNodeFunc is passed a pointer to a string that
1144  * will be stored and later freed.
1145  */
1146 typedef void     (*AddNodeFunc)    _((HashTable, char *, void *));
1147 typedef HashNode (*GetNodeFunc)    _((HashTable, const char *));
1148 typedef HashNode (*RemoveNodeFunc) _((HashTable, const char *));
1149 typedef void     (*FreeNodeFunc)   _((HashNode));
1150 typedef int      (*CompareFunc)    _((const char *, const char *));
1151 
1152 /* type of function that is passed to *
1153  * scanhashtable or scanmatchtable    */
1154 typedef void     (*ScanFunc)       _((HashNode, int));
1155 typedef void     (*ScanTabFunc)    _((HashTable, ScanFunc, int));
1156 
1157 typedef void (*PrintTableStats) _((HashTable));
1158 
1159 /* hash table for standard open hashing */
1160 
1161 struct hashtable {
1162     /* HASHTABLE DATA */
1163     int hsize;			/* size of nodes[]  (number of hash values)   */
1164     int ct;			/* number of elements                         */
1165     HashNode *nodes;		/* array of size hsize                        */
1166     void *tmpdata;
1167 
1168     /* HASHTABLE METHODS */
1169     HashFunc hash;		/* pointer to hash function for this table    */
1170     TableFunc emptytable;	/* pointer to function to empty table         */
1171     TableFunc filltable;	/* pointer to function to fill table          */
1172     CompareFunc cmpnodes;	/* pointer to function to compare two nodes     */
1173     AddNodeFunc addnode;	/* pointer to function to add new node        */
1174     GetNodeFunc getnode;	/* pointer to function to get an enabled node */
1175     GetNodeFunc getnode2;	/* pointer to function to get node            */
1176 				/* (getnode2 will ignore DISABLED flag)       */
1177     RemoveNodeFunc removenode;	/* pointer to function to delete a node       */
1178     ScanFunc disablenode;	/* pointer to function to disable a node      */
1179     ScanFunc enablenode;	/* pointer to function to enable a node       */
1180     FreeNodeFunc freenode;	/* pointer to function to free a node         */
1181     ScanFunc printnode;		/* pointer to function to print a node        */
1182     ScanTabFunc scantab;	/* pointer to function to scan table          */
1183 
1184 #ifdef HASHTABLE_INTERNAL_MEMBERS
1185     HASHTABLE_INTERNAL_MEMBERS	/* internal use in hashtable.c                */
1186 #endif
1187 };
1188 
1189 /* generic hash table node */
1190 
1191 struct hashnode {
1192     HashNode next;		/* next in hash chain */
1193     char *nam;			/* hash key           */
1194     int flags;			/* various flags      */
1195 };
1196 
1197 /* The flag to disable nodes in a hash table.  Currently  *
1198  * you can disable builtins, shell functions, aliases and *
1199  * reserved words.                                        */
1200 #define DISABLED	(1<<0)
1201 
1202 /* node in shell option table */
1203 
1204 struct optname {
1205     struct hashnode node;
1206     int optno;			/* option number */
1207 };
1208 
1209 /* node in shell reserved word hash table (reswdtab) */
1210 
1211 struct reswd {
1212     struct hashnode node;
1213     int token;			/* corresponding lexer token */
1214 };
1215 
1216 /* node in alias hash table (aliastab) */
1217 
1218 struct alias {
1219     struct hashnode node;
1220     char *text;			/* expansion of alias       */
1221     int inuse;			/* alias is being expanded  */
1222 };
1223 
1224 /* bit 0 of flags is the DISABLED flag */
1225 /* is this alias global? */
1226 #define ALIAS_GLOBAL	(1<<1)
1227 /* is this an alias for suffix handling? */
1228 #define ALIAS_SUFFIX	(1<<2)
1229 
1230 /* structure for foo=bar assignments */
1231 
1232 struct asgment {
1233     struct linknode node;
1234     char *name;
1235     int flags;
1236     union {
1237 	char *scalar;
1238 	LinkList array;
1239     } value;
1240 };
1241 
1242 /* Flags for flags element of asgment */
1243 enum {
1244     /* Array value */
1245     ASG_ARRAY = 1,
1246     /* Key / value array pair */
1247     ASG_KEY_VALUE = 2
1248 };
1249 
1250 /*
1251  * Assignment is array?
1252  */
1253 #define ASG_ARRAYP(asg) ((asg)->flags & ASG_ARRAY)
1254 
1255 /*
1256  * Assignment has value?
1257  * If the assignment is an array, then it certainly has a value --- we
1258  * can only tell if there's an explicit assignment.
1259  */
1260 
1261 #define ASG_VALUEP(asg) (ASG_ARRAYP(asg) ||			\
1262 			 ((asg)->value.scalar != (char *)0))
1263 
1264 /* node in command path hash table (cmdnamtab) */
1265 
1266 struct cmdnam {
1267     struct hashnode node;
1268     union {
1269 	char **name;		/* full pathname for external commands */
1270 	char *cmd;		/* file name for hashed commands       */
1271     }
1272     u;
1273 };
1274 
1275 /* flag for nodes explicitly added to *
1276  * cmdnamtab with hash builtin        */
1277 #define HASHED		(1<<1)
1278 
1279 /* node in shell function hash table (shfunctab) */
1280 
1281 struct shfunc {
1282     struct hashnode node;
1283     char *filename;             /* Name of file located in.
1284 				   For not yet autoloaded file, name
1285 				   of explicit directory, if not NULL. */
1286     zlong lineno;		/* line number in above file */
1287     Eprog funcdef;		/* function definition    */
1288     Eprog redir;                /* redirections to apply */
1289     Emulation_options sticky;   /* sticky emulation definitions, if any */
1290 };
1291 
1292 /* Shell function context types. */
1293 
1294 #define SFC_NONE     0		/* no function running */
1295 #define SFC_DIRECT   1		/* called directly from the user */
1296 #define SFC_SIGNAL   2		/* signal handler */
1297 #define SFC_HOOK     3		/* one of the special functions */
1298 #define SFC_WIDGET   4		/* user defined widget */
1299 #define SFC_COMPLETE 5		/* called from completion code */
1300 #define SFC_CWIDGET  6		/* new style completion widget */
1301 #define SFC_SUBST    7          /* used to perform substitution task */
1302 
1303 /* tp in funcstack */
1304 
1305 enum {
1306     FS_SOURCE,
1307     FS_FUNC,
1308     FS_EVAL
1309 };
1310 
1311 /* node in function stack */
1312 
1313 struct funcstack {
1314     Funcstack prev;		/* previous in stack */
1315     char *name;			/* name of function/sourced file called */
1316     char *filename;		/* file function resides in */
1317     char *caller;		/* name of caller */
1318     zlong flineno;		/* line number in file */
1319     zlong lineno;		/* line offset from beginning of function */
1320     int tp;     		/* type of entry: sourced file, func, eval */
1321 };
1322 
1323 /* node in list of function call wrappers */
1324 
1325 typedef int (*WrapFunc) _((Eprog, FuncWrap, char *));
1326 
1327 struct funcwrap {
1328     FuncWrap next;
1329     int flags;
1330     WrapFunc handler;
1331     Module module;
1332 };
1333 
1334 #define WRAPF_ADDED 1
1335 
1336 #define WRAPDEF(func) \
1337     { NULL, 0, func, NULL }
1338 
1339 /*
1340  * User-defined hook arrays
1341  */
1342 
1343 /* Name appended to function name to get hook array */
1344 #define HOOK_SUFFIX	"_functions"
1345 /* Length of that including NUL byte */
1346 #define HOOK_SUFFIX_LEN	11
1347 
1348 /* node in builtin command hash table (builtintab) */
1349 
1350 /*
1351  * Handling of options.
1352  *
1353  * Option strings are standard in that a trailing `:' indicates
1354  * a mandatory argument.  In addition, `::' indicates an optional
1355  * argument which must immediately follow the option letter if it is present.
1356  * `:%' indicates an optional numeric argument which may follow
1357  * the option letter or be in the next word; the only test is
1358  * that the next character is a digit, and no actual conversion is done.
1359  */
1360 
1361 #define MAX_OPS 128
1362 
1363 /* Macros taking struct option * and char argument */
1364 /* Option was set as -X */
1365 #define OPT_MINUS(ops,c)	((ops)->ind[c] & 1)
1366 /* Option was set as +X */
1367 #define OPT_PLUS(ops,c)		((ops)->ind[c] & 2)
1368 /*
1369  * Option was set any old how, maybe including an argument
1370  * (cheap test when we don't care).  Some bits of code
1371  * expect this to be 1 or 0.
1372  */
1373 #define OPT_ISSET(ops,c)	((ops)->ind[c] != 0)
1374 /* Option has an argument */
1375 #define OPT_HASARG(ops,c)	((ops)->ind[c] > 3)
1376 /* The argument for the option; not safe if it doesn't have one */
1377 #define OPT_ARG(ops,c)		((ops)->args[((ops)->ind[c] >> 2) - 1])
1378 /* Ditto, but safely returns NULL if there is no argument. */
1379 #define OPT_ARG_SAFE(ops,c)	(OPT_HASARG(ops,c) ? OPT_ARG(ops,c) : NULL)
1380 
1381 struct options {
1382     unsigned char ind[MAX_OPS];
1383     char **args;
1384     int argscount, argsalloc;
1385 };
1386 
1387 /* Flags to parseargs() */
1388 
1389 enum {
1390     PARSEARGS_TOPLEVEL = 0x1,	/* Call to initialise shell */
1391     PARSEARGS_LOGIN    = 0x2	/* Shell is login shell */
1392 };
1393 
1394 
1395 /*
1396  * Handler arguments are: builtin name, null-terminated argument
1397  * list excluding command name, option structure, the funcid element from the
1398  * builtin structure.
1399  */
1400 
1401 typedef int (*HandlerFunc) _((char *, char **, Options, int));
1402 typedef int (*HandlerFuncAssign) _((char *, char **, LinkList, Options, int));
1403 #define NULLBINCMD ((HandlerFunc) 0)
1404 
1405 struct builtin {
1406     struct hashnode node;
1407     HandlerFunc handlerfunc;	/* pointer to function that executes this builtin     */
1408     int minargs;		/* minimum number of arguments                        */
1409     int maxargs;		/* maximum number of arguments, or -1 for no limit    */
1410     int funcid;			/* xbins (see above) for overloaded handlerfuncs      */
1411     char *optstr;		/* string of legal options                            */
1412     char *defopts;		/* options set by default for overloaded handlerfuncs */
1413 };
1414 
1415 #define BUILTIN(name, flags, handler, min, max, funcid, optstr, defopts) \
1416     { { NULL, name, flags }, handler, min, max, funcid, optstr, defopts }
1417 #define BIN_PREFIX(name, flags) \
1418     BUILTIN(name, flags | BINF_PREFIX, NULLBINCMD, 0, 0, 0, NULL, NULL)
1419 
1420 /* builtin flags */
1421 /* DISABLE IS DEFINED AS (1<<0) */
1422 #define BINF_PLUSOPTS		(1<<1)	/* +xyz legal */
1423 #define BINF_PRINTOPTS		(1<<2)
1424 #define BINF_ADDED		(1<<3)	/* is in the builtins hash table */
1425 #define BINF_MAGICEQUALS	(1<<4)  /* needs automatic MAGIC_EQUAL_SUBST substitution */
1426 #define BINF_PREFIX		(1<<5)
1427 #define BINF_DASH		(1<<6)
1428 #define BINF_BUILTIN		(1<<7)
1429 #define BINF_COMMAND		(1<<8)
1430 #define BINF_EXEC		(1<<9)
1431 #define BINF_NOGLOB		(1<<10)
1432 #define BINF_PSPECIAL		(1<<11)
1433 /* Builtin option handling */
1434 #define BINF_SKIPINVALID	(1<<12)	/* Treat invalid option as argument */
1435 #define BINF_KEEPNUM		(1<<13) /* `[-+]NUM' can be an option */
1436 #define BINF_SKIPDASH		(1<<14) /* Treat `-' as argument (maybe `+') */
1437 #define BINF_DASHDASHVALID	(1<<15) /* Handle `--' even if SKIPINVALD */
1438 #define BINF_CLEARENV		(1<<16) /* new process started with cleared env */
1439 #define BINF_AUTOALL		(1<<17) /* autoload all features at once */
1440  /*
1441   * Handles options itself.  This is only useful if the option string for a
1442   * builtin with an empty option string.  It is used to indicate that "--"
1443   * does not terminate options.
1444   */
1445 #define BINF_HANDLES_OPTS	(1<<18)
1446 /*
1447  * Handles the assignment interface.  The argv list actually contains
1448  * two nested lists, the first of normal arguments, and the second of
1449  * assignment structures.
1450  */
1451 #define BINF_ASSIGN		(1<<19)
1452 
1453 /**
1454  * Parameters passed to execcmd().
1455  * These are not opaque --- they are also used by the pipeline manager.
1456  */
1457 struct execcmd_params {
1458     LinkList args;		/* All command prefixes, arguments & options */
1459     LinkList redir;		/* Redirections */
1460     Wordcode beg;		/* The code at the start of the command */
1461     Wordcode varspc;		/* The code for assignment parsed as such */
1462     Wordcode assignspc;		/* The code for assignment parsed as typeset */
1463     int type;			/* The WC_* type of the command */
1464     int postassigns;		/* The number of assignspc assiguments */
1465     int htok;			/* tokens in parameter list */
1466 };
1467 
1468 struct module {
1469     struct hashnode node;
1470     union {
1471 	void *handle;
1472 	Linkedmod linked;
1473 	char *alias;
1474     } u;
1475     LinkList autoloads;
1476     LinkList deps;
1477     int wrapper;
1478 };
1479 
1480 /* We are in the process of loading the module */
1481 #define MOD_BUSY    (1<<0)
1482 /*
1483  * We are in the process of unloading the module.
1484  * Note this is not needed to indicate a module is actually
1485  * unloaded: for that, the handle (or linked pointer) is set to NULL.
1486  */
1487 #define MOD_UNLOAD  (1<<1)
1488 /* We are in the process of setting up the module */
1489 #define MOD_SETUP   (1<<2)
1490 /* Module is statically linked into the main binary */
1491 #define MOD_LINKED  (1<<3)
1492 /* Module setup has been carried out (and module has not been finished) */
1493 #define MOD_INIT_S  (1<<4)
1494 /* Module boot has been carried out (and module has not been finished) */
1495 #define MOD_INIT_B  (1<<5)
1496 /* Module record is an alias */
1497 #define MOD_ALIAS   (1<<6)
1498 
1499 typedef int (*Module_generic_func) _((void));
1500 typedef int (*Module_void_func) _((Module));
1501 typedef int (*Module_features_func) _((Module, char ***));
1502 typedef int (*Module_enables_func) _((Module, int **));
1503 
1504 struct linkedmod {
1505     char *name;
1506     Module_void_func setup;
1507     Module_features_func features;
1508     Module_enables_func enables;
1509     Module_void_func boot;
1510     Module_void_func cleanup;
1511     Module_void_func finish;
1512 };
1513 
1514 /*
1515  * Structure combining all the concrete features available in
1516  * a module and with space for information about abstract features.
1517  */
1518 struct features {
1519     /* List of builtins provided by the module and the size thereof */
1520     Builtin bn_list;
1521     int bn_size;
1522     /* List of conditions provided by the module and the size thereof */
1523     Conddef cd_list;
1524     int cd_size;
1525     /* List of math functions provided by the module and the size thereof */
1526     MathFunc mf_list;
1527     int mf_size;
1528     /* List of parameters provided by the module and the size thereof */
1529     Paramdef pd_list;
1530     int pd_size;
1531     /* Number of abstract features */
1532     int n_abstract;
1533 };
1534 
1535 /*
1536  * Structure describing enables for one feature.
1537  */
1538 struct feature_enables {
1539     /* String feature to enable (N.B. no leading +/- allowed) */
1540     char *str;
1541     /* Optional compiled pattern for str sans +/-, NULL for string match */
1542     Patprog pat;
1543 };
1544 
1545 /* C-function hooks */
1546 
1547 typedef int (*Hookfn) _((Hookdef, void *));
1548 
1549 struct hookdef {
1550     Hookdef next;
1551     char *name;
1552     Hookfn def;
1553     int flags;
1554     LinkList funcs;
1555 };
1556 
1557 #define HOOKF_ALL 1
1558 
1559 #define HOOKDEF(name, func, flags) { NULL, name, (Hookfn) func, flags, NULL }
1560 
1561 /*
1562  * Types used in pattern matching.  Most of these longs could probably
1563  * happily be ints.
1564  */
1565 
1566 struct patprog {
1567     long		startoff;  /* length before start of programme */
1568     long		size;	   /* total size from start of struct */
1569     long		mustoff;   /* offset to string that must be present */
1570     long		patmlen;   /* length of pure string or longest match */
1571     int			globflags; /* globbing flags to set at start */
1572     int			globend;   /* globbing flags set after finish */
1573     int			flags;	   /* PAT_* flags */
1574     int			patnpar;   /* number of active parentheses */
1575     char		patstartch;
1576 };
1577 
1578 struct patstralloc {
1579     int unmetalen;		/* Unmetafied length of trial string */
1580     int unmetalenp;		/* Unmetafied length of path prefix.
1581 				   If 0, no path prefix. */
1582     char *alloced;		/* Allocated string, may be NULL */
1583     char *progstrunmeta;	/* Unmetafied pure string in pattern, cached */
1584     int progstrunmetalen;	/* Length of the foregoing */
1585 };
1586 
1587 /* Flags used in pattern matchers (Patprog) and passed down to patcompile */
1588 
1589 #define PAT_HEAPDUP	0x0000	/* Dummy flag for default behavior */
1590 #define PAT_FILE	0x0001	/* Pattern is a file name */
1591 #define PAT_FILET	0x0002	/* Pattern is top level file, affects ~ */
1592 #define PAT_ANY		0x0004	/* Match anything (cheap "*") */
1593 #define PAT_NOANCH	0x0008	/* Not anchored at end */
1594 #define PAT_NOGLD	0x0010	/* Don't glob dots */
1595 #define PAT_PURES	0x0020	/* Pattern is a pure string: set internally */
1596 #define PAT_STATIC	0x0040	/* Don't copy pattern to heap as per default */
1597 #define PAT_SCAN	0x0080	/* Scanning, so don't try must-match test */
1598 #define PAT_ZDUP        0x0100  /* Copy pattern in real memory */
1599 #define PAT_NOTSTART	0x0200	/* Start of string is not real start */
1600 #define PAT_NOTEND	0x0400	/* End of string is not real end */
1601 #define PAT_HAS_EXCLUDP	0x0800	/* (internal): top-level path1~path2. */
1602 #define PAT_LCMATCHUC   0x1000  /* equivalent to setting (#l) */
1603 
1604 /**
1605  * Indexes into the array of active pattern characters.
1606  * This must match the array zpc_chars in pattern.c.
1607  */
1608 enum zpc_chars {
1609     /*
1610      * These characters both terminate a pattern segment and
1611      * a pure string segment.
1612      */
1613     ZPC_SLASH,			/* / active as file separator */
1614     ZPC_NULL,			/* \0 as string terminator */
1615     ZPC_BAR,			/* | for "or" */
1616     ZPC_OUTPAR,			/* ) for grouping */
1617     ZPC_TILDE,			/* ~ for exclusion (extended glob) */
1618     ZPC_SEG_COUNT,              /* No. of the above characters */
1619     /*
1620      * These characters terminate a pure string segment.
1621      */
1622     ZPC_INPAR = ZPC_SEG_COUNT,  /* ( for grouping */
1623     ZPC_QUEST,			/* ? as wildcard */
1624     ZPC_STAR,			/* * as wildcard */
1625     ZPC_INBRACK,		/* [ for character class */
1626     ZPC_INANG,			/* < for numeric glob */
1627     ZPC_HAT,			/* ^ for exclusion (extended glob) */
1628     ZPC_HASH,			/* # for repetition (extended glob) */
1629     ZPC_BNULLKEEP,		/* Special backslashed null not removed */
1630     /*
1631      * These characters are only valid before a parenthesis
1632      */
1633     ZPC_NO_KSH_GLOB,
1634     ZPC_KSH_QUEST = ZPC_NO_KSH_GLOB, /* ? for ?(...) in KSH_GLOB */
1635     ZPC_KSH_STAR,               /* * for *(...) in KSH_GLOB */
1636     ZPC_KSH_PLUS,               /* + for +(...) in KSH_GLOB */
1637     ZPC_KSH_BANG,               /* ! for !(...) in KSH_GLOB */
1638     ZPC_KSH_BANG2,              /* ! for !(...) in KSH_GLOB, untokenised */
1639     ZPC_KSH_AT,                 /* @ for @(...) in KSH_GLOB */
1640     ZPC_COUNT			/* Number of special chararacters */
1641 };
1642 
1643 /*
1644  * Structure to save disables special characters for function scope.
1645  */
1646 struct zpc_disables_save {
1647     struct zpc_disables_save *next;
1648     /*
1649      * Bit vector of ZPC_COUNT disabled characters.
1650      * We'll live dangerously and assume ZPC_COUNT is no greater
1651      * than the number of bits in an unsigned int.
1652      */
1653     unsigned int disables;
1654 };
1655 
1656 typedef struct zpc_disables_save *Zpc_disables_save;
1657 
1658 /*
1659  * Special match types used in character classes.  These
1660  * are represented as tokens, with Meta added.  The character
1661  * class is represented as a metafied string, with only these
1662  * tokens special.  Note that an active leading "!" or "^" for
1663  * negation is not part of the string but is flagged in the
1664  * surrounding context.
1665  *
1666  * These types are also used in character and equivalence classes
1667  * in completion matching.
1668  *
1669  * This must be kept ordered by the array colon_stuffs in pattern.c.
1670  */
1671 /* Special value for first definition */
1672 #define PP_FIRST  1
1673 /* POSIX-defined types:  [:alpha:] etc. */
1674 #define PP_ALPHA  1
1675 #define PP_ALNUM  2
1676 #define PP_ASCII  3
1677 #define PP_BLANK  4
1678 #define PP_CNTRL  5
1679 #define PP_DIGIT  6
1680 #define PP_GRAPH  7
1681 #define PP_LOWER  8
1682 #define PP_PRINT  9
1683 #define PP_PUNCT  10
1684 #define PP_SPACE  11
1685 #define PP_UPPER  12
1686 #define PP_XDIGIT 13
1687 /* Zsh additions:  [:IDENT:] etc. */
1688 #define PP_IDENT  14
1689 #define PP_IFS    15
1690 #define PP_IFSSPACE   16
1691 #define PP_WORD   17
1692 #define PP_INCOMPLETE 18
1693 #define PP_INVALID 19
1694 /* Special value for last definition */
1695 #define PP_LAST   19
1696 
1697 /* Unknown type.  Not used in a valid token. */
1698 #define PP_UNKWN  20
1699 /* Range: token followed by the (possibly multibyte) start and end */
1700 #define PP_RANGE  21
1701 
1702 /*
1703  * Argument to get_match_ret() in glob.c
1704  */
1705 struct imatchdata {
1706     /* Metafied trial string */
1707     char *mstr;
1708     /* Its length */
1709     int mlen;
1710     /* Unmetafied string */
1711     char *ustr;
1712     /* Its length */
1713     int ulen;
1714     /* Flags (SUB_*) */
1715     int flags;
1716     /* Replacement string (metafied) */
1717     char *replstr;
1718     /*
1719      * List of bits of matches to concatenate with replacement string.
1720      * The data is a struct repldata.  It is not used in cases like
1721      * ${...//#foo/bar} even though SUB_GLOBAL is set, since the match
1722      * is anchored.  It goes on the heap.
1723      */
1724     LinkList repllist;
1725 };
1726 
1727 /* Globbing flags: lower 8 bits gives approx count */
1728 #define GF_LCMATCHUC	0x0100
1729 #define GF_IGNCASE	0x0200
1730 #define GF_BACKREF	0x0400
1731 #define GF_MATCHREF	0x0800
1732 #define GF_MULTIBYTE	0x1000	/* Use multibyte if supported by build */
1733 
1734 enum {
1735     /* Valid multibyte character from charref */
1736     ZMB_VALID,
1737     /* Incomplete multibyte character from charref */
1738     ZMB_INCOMPLETE,
1739     /* Invalid multibyte character charref */
1740     ZMB_INVALID
1741 };
1742 
1743 /* Dummy Patprog pointers. Used mainly in executable code, but the
1744  * pattern code needs to know about it, too. */
1745 
1746 #define dummy_patprog1 ((Patprog) 1)
1747 #define dummy_patprog2 ((Patprog) 2)
1748 
1749 /* standard node types for get/set/unset union in parameter */
1750 
1751 /*
1752  * note non-standard const in pointer declaration: structures are
1753  * assumed to be read-only.
1754  */
1755 typedef const struct gsu_scalar *GsuScalar;
1756 typedef const struct gsu_integer *GsuInteger;
1757 typedef const struct gsu_float *GsuFloat;
1758 typedef const struct gsu_array *GsuArray;
1759 typedef const struct gsu_hash *GsuHash;
1760 
1761 struct gsu_scalar {
1762     char *(*getfn) _((Param));
1763     void (*setfn) _((Param, char  *));
1764     void (*unsetfn) _((Param, int));
1765 };
1766 
1767 struct gsu_integer {
1768     zlong (*getfn) _((Param));
1769     void (*setfn) _((Param, zlong));
1770     void (*unsetfn) _((Param, int));
1771 };
1772 
1773 struct gsu_float {
1774     double (*getfn) _((Param));
1775     void (*setfn) _((Param, double));
1776     void (*unsetfn) _((Param, int));
1777 };
1778 
1779 struct gsu_array {
1780     char **(*getfn) _((Param));
1781     void (*setfn) _((Param, char **));
1782     void (*unsetfn) _((Param, int));
1783 };
1784 
1785 struct gsu_hash {
1786     HashTable (*getfn) _((Param));
1787     void (*setfn) _((Param, HashTable));
1788     void (*unsetfn) _((Param, int));
1789 };
1790 
1791 
1792 /* node used in parameter hash table (paramtab) */
1793 
1794 struct param {
1795     struct hashnode node;
1796 
1797     /* the value of this parameter */
1798     union {
1799 	void *data;		/* used by special parameter functions    */
1800 	char **arr;		/* value if declared array   (PM_ARRAY)   */
1801 	char *str;		/* value if declared string  (PM_SCALAR)  */
1802 	zlong val;		/* value if declared integer (PM_INTEGER) */
1803 	zlong *valptr;		/* value if special pointer to integer */
1804 	double dval;		/* value if declared float
1805 				                    (PM_EFLOAT|PM_FFLOAT) */
1806         HashTable hash;		/* value if declared assoc   (PM_HASHED)  */
1807     } u;
1808 
1809     /*
1810      * get/set/unset methods.
1811      *
1812      * Unlike the data union, this points to a single instance
1813      * for every type (although there are special types, e.g.
1814      * tied arrays have a different gsu_scalar struct from the
1815      * normal one).  It's really a poor man's vtable.
1816      */
1817     union {
1818 	GsuScalar s;
1819 	GsuInteger i;
1820 	GsuFloat f;
1821 	GsuArray a;
1822 	GsuHash h;
1823     } gsu;
1824 
1825     int base;			/* output base or floating point prec    */
1826     int width;			/* field width                           */
1827     char *env;			/* location in environment, if exported  */
1828     char *ename;		/* name of corresponding environment var */
1829     Param old;			/* old struct for use with local         */
1830     int level;			/* if (old != NULL), level of localness  */
1831 };
1832 
1833 /* structure stored in struct param's u.data by tied arrays */
1834 struct tieddata {
1835     char ***arrptr;		/* pointer to corresponding array */
1836     int joinchar;		/* character used to join arrays */
1837 };
1838 
1839 /* flags for parameters */
1840 
1841 /* parameter types */
1842 #define PM_SCALAR	0	/* scalar                                   */
1843 #define PM_ARRAY	(1<<0)	/* array                                    */
1844 #define PM_INTEGER	(1<<1)	/* integer                                  */
1845 #define PM_EFLOAT	(1<<2)	/* double with %e output		    */
1846 #define PM_FFLOAT	(1<<3)	/* double with %f output		    */
1847 #define PM_HASHED	(1<<4)	/* association                              */
1848 
1849 #define PM_TYPE(X) \
1850   (X & (PM_SCALAR|PM_INTEGER|PM_EFLOAT|PM_FFLOAT|PM_ARRAY|PM_HASHED))
1851 
1852 #define PM_LEFT		(1<<5)	/* left justify, remove leading blanks      */
1853 #define PM_RIGHT_B	(1<<6)	/* right justify, fill with leading blanks  */
1854 #define PM_RIGHT_Z	(1<<7)	/* right justify, fill with leading zeros   */
1855 #define PM_LOWER	(1<<8)	/* all lower case                           */
1856 
1857 /* The following are the same since they *
1858  * both represent -u option to typeset   */
1859 #define PM_UPPER	(1<<9)	/* all upper case                           */
1860 #define PM_UNDEFINED	(1<<9)	/* undefined (autoloaded) shell function    */
1861 
1862 #define PM_READONLY	(1<<10)	/* readonly                                 */
1863 #define PM_TAGGED	(1<<11)	/* tagged                                   */
1864 #define PM_EXPORTED	(1<<12)	/* exported                                 */
1865 #define PM_ABSPATH_USED (1<<12) /* (function): loaded using absolute path   */
1866 
1867 /* The following are the same since they *
1868  * both represent -U option to typeset   */
1869 #define PM_UNIQUE	(1<<13)	/* remove duplicates                        */
1870 #define PM_UNALIASED	(1<<13)	/* (function) do not expand aliases when autoloading   */
1871 
1872 #define PM_HIDE		(1<<14)	/* Special behaviour hidden by local        */
1873 #define PM_CUR_FPATH    (1<<14) /* (function): can use $fpath with filename */
1874 #define PM_HIDEVAL	(1<<15)	/* Value not shown in `typeset' commands    */
1875 #define PM_WARNNESTED   (1<<15) /* (function): non-recursive WARNNESTEDVAR  */
1876 #define PM_TIED 	(1<<16)	/* array tied to colon-path or v.v.         */
1877 #define PM_TAGGED_LOCAL (1<<16) /* (function): non-recursive PM_TAGGED      */
1878 
1879 /* Remaining flags do not correspond directly to command line arguments */
1880 #define PM_DONTIMPORT_SUID (1<<17) /* do not import if running setuid */
1881 #define PM_LOADDIR      (1<<17) /* (function) filename gives load directory */
1882 #define PM_SINGLE       (1<<18) /* special can only have a single instance  */
1883 #define PM_ANONYMOUS    (1<<18) /* (function) anonymous function            */
1884 #define PM_LOCAL	(1<<19) /* this parameter will be made local        */
1885 #define PM_KSHSTORED	(1<<19) /* (function) stored in ksh form              */
1886 #define PM_SPECIAL	(1<<20) /* special builtin parameter                */
1887 #define PM_ZSHSTORED	(1<<20) /* (function) stored in zsh form              */
1888 #define PM_RO_BY_DESIGN (1<<21) /* to distinguish from specials that can be
1889 				   made read-only by the user               */
1890 #define PM_READONLY_SPECIAL (PM_SPECIAL|PM_READONLY|PM_RO_BY_DESIGN)
1891 #define PM_DONTIMPORT	(1<<22)	/* do not import this variable              */
1892 #define PM_RESTRICTED	(1<<23) /* cannot be changed in restricted mode     */
1893 #define PM_UNSET	(1<<24)	/* has null value                           */
1894 #define PM_REMOVABLE	(1<<25)	/* special can be removed from paramtab     */
1895 #define PM_AUTOLOAD	(1<<26) /* autoloaded from module                   */
1896 #define PM_NORESTORE	(1<<27)	/* do not restore value of local special    */
1897 #define PM_AUTOALL	(1<<27) /* autoload all features in module
1898 				 * when loading: valid only if PM_AUTOLOAD
1899 				 * is also present.
1900 				 */
1901 #define PM_HASHELEM     (1<<28) /* is a hash-element */
1902 #define PM_NAMEDDIR     (1<<29) /* has a corresponding nameddirtab entry    */
1903 
1904 /* The option string corresponds to the first of the variables above */
1905 #define TYPESET_OPTSTR "aiEFALRZlurtxUhHTkz"
1906 
1907 /* These typeset options take an optional numeric argument */
1908 #define TYPESET_OPTNUM "LRZiEF"
1909 
1910 /* Flags for extracting elements of arrays and associative arrays */
1911 #define SCANPM_WANTVALS   (1<<0) /* Return value includes hash values */
1912 #define SCANPM_WANTKEYS   (1<<1) /* Return value includes hash keys */
1913 #define SCANPM_WANTINDEX  (1<<2) /* Return value includes array index */
1914 #define SCANPM_MATCHKEY   (1<<3) /* Subscript matched against key */
1915 #define SCANPM_MATCHVAL   (1<<4) /* Subscript matched against value */
1916 #define SCANPM_MATCHMANY  (1<<5) /* Subscript matched repeatedly, return all */
1917 #define SCANPM_ASSIGNING  (1<<6) /* Assigning whole array/hash */
1918 #define SCANPM_KEYMATCH   (1<<7) /* keys of hash treated as patterns */
1919 #define SCANPM_DQUOTED    (1<<8) /* substitution was double-quoted
1920 				  * (only used for testing early end of
1921 				  * subscript)
1922 				  */
1923 #define SCANPM_ARRONLY    (1<<9) /* value is array but we don't
1924 				  * necessarily want to match multiple
1925 				  * elements
1926 				  */
1927 #define SCANPM_CHECKING   (1<<10) /* Check if set, no need to create */
1928 /* "$foo[@]"-style substitution
1929  * Only sign bit is significant
1930  */
1931 #define SCANPM_ISVAR_AT   ((int)(((unsigned int)-1)<<15))
1932 
1933 /*
1934  * Flags for doing matches inside parameter substitutions, i.e.
1935  * ${...#...} and friends.  This could be an enum, but so
1936  * could a lot of other things.
1937  */
1938 
1939 #define SUB_END		0x0001	/* match end instead of beginning, % or %%  */
1940 #define SUB_LONG	0x0002	/* % or # doubled, get longest match */
1941 #define SUB_SUBSTR	0x0004	/* match a substring */
1942 #define SUB_MATCH	0x0008	/* include the matched portion */
1943 #define SUB_REST	0x0010	/* include the unmatched portion */
1944 #define SUB_BIND	0x0020	/* index of beginning of string */
1945 #define SUB_EIND	0x0040	/* index of end of string */
1946 #define SUB_LEN		0x0080	/* length of match */
1947 #define SUB_ALL		0x0100	/* match complete string */
1948 #define SUB_GLOBAL	0x0200	/* global substitution ${..//all/these} */
1949 #define SUB_DOSUBST	0x0400	/* replacement string needs substituting */
1950 #define SUB_RETFAIL	0x0800  /* return status 0 if no match */
1951 #define SUB_START	0x1000  /* force match at start with SUB_END
1952 				 * and no SUB_SUBSTR */
1953 #define SUB_LIST	0x2000  /* no substitution, return list of matches */
1954 
1955 /*
1956  * Structure recording multiple matches inside a test string.
1957  * b and e are the beginning and end of the match.
1958  * replstr is the replacement string, if any.
1959  */
1960 struct repldata {
1961     int b, e;			/* beginning and end of chunk to replace */
1962     char *replstr;		/* replacement string to use */
1963 };
1964 typedef struct repldata *Repldata;
1965 
1966 /*
1967  * Flags to zshtokenize.
1968  */
1969 enum {
1970     /* Do glob substitution */
1971     ZSHTOK_SUBST = 0x0001,
1972     /* Use sh-style globbing */
1973     ZSHTOK_SHGLOB = 0x0002
1974 };
1975 
1976 /* Flags as the second argument to prefork */
1977 enum {
1978     /* argument handled like typeset foo=bar */
1979     PREFORK_TYPESET       = 0x01,
1980     /* argument handled like the RHS of foo=bar */
1981     PREFORK_ASSIGN        = 0x02,
1982     /* single word substitution */
1983     PREFORK_SINGLE        = 0x04,
1984     /* explicitly split nested substitution */
1985     PREFORK_SPLIT         = 0x08,
1986     /* SHWORDSPLIT in parameter expn */
1987     PREFORK_SHWORDSPLIT   = 0x10,
1988     /* SHWORDSPLIT forced off in nested subst */
1989     PREFORK_NOSHWORDSPLIT = 0x20,
1990     /* Prefork is part of a parameter subexpression */
1991     PREFORK_SUBEXP        = 0x40,
1992     /* Prefork detected an assignment list with [key]=value syntax,
1993      * Only used on return from prefork, not meaningful passed down.
1994      * Also used as flag to globlist.
1995      */
1996     PREFORK_KEY_VALUE     = 0x80,
1997     /* No untokenise: used only as flag to globlist */
1998     PREFORK_NO_UNTOK      = 0x100
1999 };
2000 
2001 /*
2002  * Bit flags passed back from multsub() to paramsubst().
2003  * Some flags go from a nested parmsubst() through the enclosing
2004  * stringsubst() and prefork().
2005  */
2006 enum {
2007     /*
2008      * Set if the string had whitespace at the start
2009      * that should cause word splitting against any preceding string.
2010      */
2011     MULTSUB_WS_AT_START = 1,
2012     /*
2013      * Set if the string had whitespace at the end
2014      * that should cause word splitting against any following string.
2015      */
2016     MULTSUB_WS_AT_END   = 2,
2017     /*
2018      * Set by nested paramsubst() to indicate the return
2019      * value is a parameter name, rather than a value.
2020      */
2021     MULTSUB_PARAM_NAME  = 4
2022 };
2023 
2024 /*
2025  * Structure for adding parameters in a module.
2026  * The flags should declare the type; note PM_SCALAR is zero.
2027  *
2028  * Special hashes are recognized by getnfn so the PM_HASHED
2029  * is optional.  These get slightly non-standard attention:
2030  * the function createspecialhash is used to create them.
2031  *
2032  * The get/set/unset attribute may be NULL; in that case the
2033  * parameter is assigned methods suitable for handling the
2034  * tie variable var, if that is not NULL, else standard methods.
2035  *
2036  * pm is set when the parameter is added to the parameter table
2037  * and serves as a flag that the parameter has been added.
2038  */
2039 struct paramdef {
2040     char *name;
2041     int flags;
2042     void *var;			/* tied internal variable, if any */
2043     const void *gsu;		/* get/set/unset structure, if special */
2044     GetNodeFunc getnfn;		/* function to get node, if special hash */
2045     ScanTabFunc scantfn;	/* function to scan table, if special hash */
2046     Param pm;			/* structure inserted into param table */
2047 };
2048 
2049 /*
2050  * Shorthand for common uses of adding parameters, with no special
2051  * hash properties.
2052  */
2053 #define PARAMDEF(name, flags, var, gsu) \
2054     { name, flags, (void *) var, (void *) gsu, \
2055 	    NULL, NULL, NULL \
2056     }
2057 /*
2058  * Note that the following definitions are appropriate for defining
2059  * parameters that reference a variable (var).  Hence the get/set/unset
2060  * methods used will assume var needs dereferencing to get the value.
2061  */
2062 #define INTPARAMDEF(name, var) \
2063     { name, PM_INTEGER, (void *) var, NULL,  NULL, NULL, NULL }
2064 #define STRPARAMDEF(name, var) \
2065     { name, PM_SCALAR, (void *) var, NULL, NULL, NULL, NULL }
2066 #define ARRPARAMDEF(name, var) \
2067     { name, PM_ARRAY, (void *) var, NULL, NULL, NULL, NULL }
2068 /*
2069  * The following is appropriate for a module function that behaves
2070  * in a special fashion.  Parameters used in a module that don't
2071  * have special behaviour shouldn't be declared in a table but
2072  * should just be added with the standard parameter functions.
2073  *
2074  * These parameters are not marked as removable, since they
2075  * shouldn't be loaded as local parameters, unlike the special
2076  * Zle parameters that are added and removed on each call to Zle.
2077  * We add the PM_REMOVABLE flag when removing the feature corresponding
2078  * to the parameter.
2079  */
2080 #define SPECIALPMDEF(name, flags, gsufn, getfn, scanfn) \
2081     { name, flags | PM_SPECIAL | PM_HIDE | PM_HIDEVAL, \
2082 	    NULL, gsufn, getfn, scanfn, NULL }
2083 
2084 /*
2085  * Flags for assignsparam and assignaparam.
2086  */
2087 enum {
2088     /* Add to rather than override value */
2089     ASSPM_AUGMENT = 1 << 0,
2090     /* Test for warning if creating global variable in function */
2091     ASSPM_WARN_CREATE = 1 << 1,
2092     /* Test for warning if using nested variable in function */
2093     ASSPM_WARN_NESTED = 1 << 2,
2094     ASSPM_WARN = (ASSPM_WARN_CREATE|ASSPM_WARN_NESTED),
2095     /* Import from environment, so exercise care evaluating value */
2096     ASSPM_ENV_IMPORT = 1 << 3,
2097     /* Array is key / value pairs.
2098      * This is normal for associative arrays but variant behaviour for
2099      * normal arrays.
2100      */
2101     ASSPM_KEY_VALUE = 1 << 4
2102 };
2103 
2104 /* node for named directory hash table (nameddirtab) */
2105 
2106 struct nameddir {
2107     struct hashnode node;
2108     char *dir;			/* the directory in full            */
2109     int diff;			/* strlen(.dir) - strlen(.nam)      */
2110 };
2111 
2112 /* flags for named directories */
2113 /* DISABLED is defined (1<<0) */
2114 #define ND_USERNAME	(1<<1)	/* nam is actually a username       */
2115 #define ND_NOABBREV	(1<<2)	/* never print as abbrev (PWD or OLDPWD) */
2116 
2117 /* Storage for single group/name mapping */
2118 typedef struct {
2119     /* Name of group */
2120     char *name;
2121     /* Group identifier */
2122     gid_t gid;
2123 } groupmap;
2124 typedef groupmap *Groupmap;
2125 
2126 /* Storage for a set of group/name mappings */
2127 typedef struct {
2128     /* The set of name to gid mappings */
2129     Groupmap array;
2130     /* A count of the valid entries in groupmap. */
2131     int num;
2132 } groupset;
2133 typedef groupset *Groupset;
2134 
2135 /* flags for controlling printing of hash table nodes */
2136 #define PRINT_NAMEONLY		(1<<0)
2137 #define PRINT_TYPE		(1<<1)
2138 #define PRINT_LIST		(1<<2)
2139 #define PRINT_KV_PAIR		(1<<3)
2140 #define PRINT_INCLUDEVALUE	(1<<4)
2141 #define PRINT_TYPESET		(1<<5)
2142 #define PRINT_LINE	        (1<<6)
2143 #define PRINT_POSIX_EXPORT	(1<<7)
2144 #define PRINT_POSIX_READONLY	(1<<8)
2145 
2146 /* flags for printing for the whence builtin */
2147 #define PRINT_WHENCE_CSH	(1<<7)
2148 #define PRINT_WHENCE_VERBOSE	(1<<8)
2149 #define PRINT_WHENCE_SIMPLE	(1<<9)
2150 #define PRINT_WHENCE_FUNCDEF	(1<<10)
2151 #define PRINT_WHENCE_WORD	(1<<11)
2152 
2153 /* Return values from loop() */
2154 
2155 enum loop_return {
2156     /* Loop executed OK */
2157     LOOP_OK,
2158     /* Loop executed no code */
2159     LOOP_EMPTY,
2160     /* Loop encountered an error */
2161     LOOP_ERROR
2162 };
2163 
2164 /* Return values from source() */
2165 
2166 enum source_return {
2167     /* Source ran OK */
2168     SOURCE_OK = 0,
2169     /* File not found */
2170     SOURCE_NOT_FOUND = 1,
2171     /* Internal error sourcing file */
2172     SOURCE_ERROR = 2
2173 };
2174 
2175 enum noerrexit_bits {
2176     /* Suppress ERR_EXIT and traps: global */
2177     NOERREXIT_EXIT = 1,
2178     /* Suppress ERR_RETURN: per function call */
2179     NOERREXIT_RETURN = 2,
2180     /* NOERREXIT only needed on way down */
2181     NOERREXIT_UNTIL_EXEC = 4,
2182     /* Force exit on SIGINT */
2183     NOERREXIT_SIGNAL = 8
2184 };
2185 
2186 /***********************************/
2187 /* Definitions for history control */
2188 /***********************************/
2189 
2190 /* history entry */
2191 
2192 struct histent {
2193     struct hashnode node;
2194 
2195     Histent up;			/* previous line (moving upward)    */
2196     Histent down;		/* next line (moving downward)      */
2197     char *zle_text;		/* the edited history line,
2198 				 * a metafied, NULL-terminated string,
2199 				 * i.e the same format as the original
2200 				 * entry
2201 				 */
2202     time_t stim;		/* command started time (datestamp) */
2203     time_t ftim;		/* command finished time            */
2204     short *words;		/* Position of words in history     */
2205 				/*   line:  as pairs of start, end  */
2206     int nwords;			/* Number of words in history line  */
2207     zlong histnum;		/* A sequential history number      */
2208 };
2209 
2210 #define HIST_MAKEUNIQUE	0x00000001	/* Kill this new entry if not unique */
2211 #define HIST_OLD	0x00000002	/* Command is already written to disk*/
2212 #define HIST_READ	0x00000004	/* Command was read back from disk*/
2213 #define HIST_DUP	0x00000008	/* Command duplicates a later line */
2214 #define HIST_FOREIGN	0x00000010	/* Command came from another shell */
2215 #define HIST_TMPSTORE	0x00000020	/* Kill when user enters another cmd */
2216 #define HIST_NOWRITE	0x00000040	/* Keep internally but don't write */
2217 
2218 #define GETHIST_UPWARD  (-1)
2219 #define GETHIST_DOWNWARD  1
2220 #define GETHIST_EXACT     0
2221 
2222 /* Parts of the code where history expansion is disabled *
2223  * should be within a pair of STOPHIST ... ALLOWHIST     */
2224 
2225 #define STOPHIST (stophist += 4);
2226 #define ALLOWHIST (stophist -= 4);
2227 
2228 #define HISTFLAG_DONE   1
2229 #define HISTFLAG_NOEXEC 2
2230 #define HISTFLAG_RECALL 4
2231 #define HISTFLAG_SETTY  8
2232 
2233 #define HFILE_APPEND		0x0001
2234 #define HFILE_SKIPOLD		0x0002
2235 #define HFILE_SKIPDUPS		0x0004
2236 #define HFILE_SKIPFOREIGN	0x0008
2237 #define HFILE_FAST		0x0010
2238 #define HFILE_NO_REWRITE	0x0020
2239 #define HFILE_USE_OPTIONS	0x8000
2240 
2241 /*
2242  * Flags argument to bufferwords() used
2243  * also by lexflags variable.
2244  */
2245 /*
2246  * Kick the lexer into special string-analysis
2247  * mode without parsing.  Any bit set in
2248  * the flags has this effect, but this
2249  * has otherwise all the default effects.
2250  */
2251 #define LEXFLAGS_ACTIVE		0x0001
2252 /*
2253  * Being used from zle.  This is slightly more intrusive
2254  * (=> grotesquely non-modular) than use from within
2255  * the main shell, so it's a separate flag.
2256  */
2257 #define LEXFLAGS_ZLE		0x0002
2258 /*
2259  * Parse comments and treat each comment as a single string
2260  */
2261 #define LEXFLAGS_COMMENTS_KEEP	0x0004
2262 /*
2263  * Parse comments and strip them.
2264  */
2265 #define LEXFLAGS_COMMENTS_STRIP	0x0008
2266 /*
2267  * Either of the above
2268  */
2269 #define LEXFLAGS_COMMENTS (LEXFLAGS_COMMENTS_KEEP|LEXFLAGS_COMMENTS_STRIP)
2270 /*
2271  * Treat newlines as whitespace
2272  */
2273 #define LEXFLAGS_NEWLINE	0x0010
2274 
2275 /*******************************************/
2276 /* Definitions for programmable completion */
2277 /*******************************************/
2278 
2279 /* Nothing special. */
2280 #define IN_NOTHING 0
2281 /* In command position. */
2282 #define IN_CMD     1
2283 /* In a mathematical environment. */
2284 #define IN_MATH    2
2285 /* In a condition. */
2286 #define IN_COND    3
2287 /* In a parameter assignment (e.g. `foo=bar'). */
2288 #define IN_ENV     4
2289 /* In a parameter name in an assignment. */
2290 #define IN_PAR     5
2291 
2292 
2293 /******************************/
2294 /* Definition for zsh options */
2295 /******************************/
2296 
2297 /* Possible values of emulation */
2298 
2299 #define EMULATE_CSH  (1<<1) /* C shell */
2300 #define EMULATE_KSH  (1<<2) /* Korn shell */
2301 #define EMULATE_SH   (1<<3) /* Bourne shell */
2302 #define EMULATE_ZSH  (1<<4) /* `native' mode */
2303 
2304 /* Test for a shell emulation.  Use this rather than emulation directly. */
2305 #define EMULATION(X)	(emulation & (X))
2306 
2307 /* Return only base shell emulation field. */
2308 #define SHELL_EMULATION()	(emulation & ((1<<5)-1))
2309 
2310 /* Additional flags */
2311 
2312 #define EMULATE_FULLY (1<<5) /* "emulate -R" in effect */
2313 /*
2314  * Higher bits are used in options.c, record lowest unused bit...
2315  */
2316 #define EMULATE_UNUSED (1<<6)
2317 
2318 /* option indices */
2319 
2320 enum {
2321     OPT_INVALID,
2322     ALIASESOPT,
2323     ALIASFUNCDEF,
2324     ALLEXPORT,
2325     ALWAYSLASTPROMPT,
2326     ALWAYSTOEND,
2327     APPENDHISTORY,
2328     AUTOCD,
2329     AUTOCONTINUE,
2330     AUTOLIST,
2331     AUTOMENU,
2332     AUTONAMEDIRS,
2333     AUTOPARAMKEYS,
2334     AUTOPARAMSLASH,
2335     AUTOPUSHD,
2336     AUTOREMOVESLASH,
2337     AUTORESUME,
2338     BADPATTERN,
2339     BANGHIST,
2340     BAREGLOBQUAL,
2341     BASHAUTOLIST,
2342     BASHREMATCH,
2343     BEEP,
2344     BGNICE,
2345     BRACECCL,
2346     BSDECHO,
2347     CASEGLOB,
2348     CASEMATCH,
2349     CBASES,
2350     CDABLEVARS,
2351     CDSILENT,
2352     CHASEDOTS,
2353     CHASELINKS,
2354     CHECKJOBS,
2355     CHECKRUNNINGJOBS,
2356     CLOBBER,
2357     APPENDCREATE,
2358     COMBININGCHARS,
2359     COMPLETEALIASES,
2360     COMPLETEINWORD,
2361     CORRECT,
2362     CORRECTALL,
2363     CONTINUEONERROR,
2364     CPRECEDENCES,
2365     CSHJUNKIEHISTORY,
2366     CSHJUNKIELOOPS,
2367     CSHJUNKIEQUOTES,
2368     CSHNULLCMD,
2369     CSHNULLGLOB,
2370     DEBUGBEFORECMD,
2371     EMACSMODE,
2372     EQUALS,
2373     ERREXIT,
2374     ERRRETURN,
2375     EXECOPT,
2376     EXTENDEDGLOB,
2377     EXTENDEDHISTORY,
2378     EVALLINENO,
2379     FLOWCONTROL,
2380     FORCEFLOAT,
2381     FUNCTIONARGZERO,
2382     GLOBOPT,
2383     GLOBALEXPORT,
2384     GLOBALRCS,
2385     GLOBASSIGN,
2386     GLOBCOMPLETE,
2387     GLOBDOTS,
2388     GLOBSTARSHORT,
2389     GLOBSUBST,
2390     HASHCMDS,
2391     HASHDIRS,
2392     HASHEXECUTABLESONLY,
2393     HASHLISTALL,
2394     HISTALLOWCLOBBER,
2395     HISTBEEP,
2396     HISTEXPIREDUPSFIRST,
2397     HISTFCNTLLOCK,
2398     HISTFINDNODUPS,
2399     HISTIGNOREALLDUPS,
2400     HISTIGNOREDUPS,
2401     HISTIGNORESPACE,
2402     HISTLEXWORDS,
2403     HISTNOFUNCTIONS,
2404     HISTNOSTORE,
2405     HISTREDUCEBLANKS,
2406     HISTSAVEBYCOPY,
2407     HISTSAVENODUPS,
2408     HISTSUBSTPATTERN,
2409     HISTVERIFY,
2410     HUP,
2411     IGNOREBRACES,
2412     IGNORECLOSEBRACES,
2413     IGNOREEOF,
2414     INCAPPENDHISTORY,
2415     INCAPPENDHISTORYTIME,
2416     INTERACTIVE,
2417     INTERACTIVECOMMENTS,
2418     KSHARRAYS,
2419     KSHAUTOLOAD,
2420     KSHGLOB,
2421     KSHOPTIONPRINT,
2422     KSHTYPESET,
2423     KSHZEROSUBSCRIPT,
2424     LISTAMBIGUOUS,
2425     LISTBEEP,
2426     LISTPACKED,
2427     LISTROWSFIRST,
2428     LISTTYPES,
2429     LOCALLOOPS,
2430     LOCALOPTIONS,
2431     LOCALPATTERNS,
2432     LOCALTRAPS,
2433     LOGINSHELL,
2434     LONGLISTJOBS,
2435     MAGICEQUALSUBST,
2436     MAILWARNING,
2437     MARKDIRS,
2438     MENUCOMPLETE,
2439     MONITOR,
2440     MULTIBYTE,
2441     MULTIFUNCDEF,
2442     MULTIOS,
2443     NOMATCH,
2444     NOTIFY,
2445     NULLGLOB,
2446     NUMERICGLOBSORT,
2447     OCTALZEROES,
2448     OVERSTRIKE,
2449     PATHDIRS,
2450     PATHSCRIPT,
2451     PIPEFAIL,
2452     POSIXALIASES,
2453     POSIXARGZERO,
2454     POSIXBUILTINS,
2455     POSIXCD,
2456     POSIXIDENTIFIERS,
2457     POSIXJOBS,
2458     POSIXSTRINGS,
2459     POSIXTRAPS,
2460     PRINTEIGHTBIT,
2461     PRINTEXITVALUE,
2462     PRIVILEGED,
2463     PROMPTBANG,
2464     PROMPTCR,
2465     PROMPTPERCENT,
2466     PROMPTSP,
2467     PROMPTSUBST,
2468     PUSHDIGNOREDUPS,
2469     PUSHDMINUS,
2470     PUSHDSILENT,
2471     PUSHDTOHOME,
2472     RCEXPANDPARAM,
2473     RCQUOTES,
2474     RCS,
2475     RECEXACT,
2476     REMATCHPCRE,
2477     RESTRICTED,
2478     RMSTARSILENT,
2479     RMSTARWAIT,
2480     SHAREHISTORY,
2481     SHFILEEXPANSION,
2482     SHGLOB,
2483     SHINSTDIN,
2484     SHNULLCMD,
2485     SHOPTIONLETTERS,
2486     SHORTLOOPS,
2487     SHWORDSPLIT,
2488     SINGLECOMMAND,
2489     SINGLELINEZLE,
2490     SOURCETRACE,
2491     SUNKEYBOARDHACK,
2492     TRANSIENTRPROMPT,
2493     TRAPSASYNC,
2494     TYPESETSILENT,
2495     UNSET,
2496     VERBOSE,
2497     VIMODE,
2498     WARNCREATEGLOBAL,
2499     WARNNESTEDVAR,
2500     XTRACE,
2501     USEZLE,
2502     DVORAK,
2503     OPT_SIZE
2504 };
2505 
2506 /*
2507  * Size required to fit an option number.
2508  * If OPT_SIZE goes above 256 this will need to expand.
2509  */
2510 typedef unsigned char OptIndex;
2511 
2512 #undef isset
2513 #define isset(X) (opts[X])
2514 #define unset(X) (!opts[X])
2515 
2516 #define interact (isset(INTERACTIVE))
2517 #define jobbing  (isset(MONITOR))
2518 #define islogin  (isset(LOGINSHELL))
2519 
2520 /*
2521  * Record of emulation and options that need to be set
2522  * for a full "emulate".
2523  */
2524 struct emulation_options {
2525     /* The emulation itself */
2526     int emulation;
2527     /* The number of options in on_opts. */
2528     int n_on_opts;
2529     /* The number of options in off_opts. */
2530     int n_off_opts;
2531     /*
2532      * Array of options to be turned on.
2533      * Only options specified explicitly in the emulate command
2534      * are recorded.  Null if n_on_opts is zero.
2535      */
2536     OptIndex *on_opts;
2537     /* Array of options to be turned off, similar. */
2538     OptIndex *off_opts;
2539 };
2540 
2541 /***********************************************/
2542 /* Definitions for terminal and display control */
2543 /***********************************************/
2544 
2545 /* tty state structure */
2546 
2547 struct ttyinfo {
2548 #ifdef HAVE_TERMIOS_H
2549     struct termios tio;
2550 #else
2551 # ifdef HAVE_TERMIO_H
2552     struct termio tio;
2553 # else
2554     struct sgttyb sgttyb;
2555     int lmodes;
2556     struct tchars tchars;
2557     struct ltchars ltchars;
2558 # endif
2559 #endif
2560 #ifdef TIOCGWINSZ
2561     struct winsize winsize;
2562 #endif
2563 };
2564 
2565 #ifndef __INTERIX
2566 /* defines for whether tabs expand to spaces */
2567 #if defined(HAVE_TERMIOS_H) || defined(HAVE_TERMIO_H)
2568 #define SGTTYFLAG       shttyinfo.tio.c_oflag
2569 #else   /* we're using sgtty */
2570 #define SGTTYFLAG       shttyinfo.sgttyb.sg_flags
2571 #endif
2572 # ifdef TAB3
2573 #define SGTABTYPE       TAB3
2574 # else
2575 #  ifdef OXTABS
2576 #define SGTABTYPE       OXTABS
2577 #  else
2578 #   ifdef XTABS
2579 #define SGTABTYPE       XTABS
2580 #   endif
2581 #  endif
2582 # endif
2583 #endif
2584 
2585 /* flags for termflags */
2586 
2587 #define TERM_BAD	0x01	/* terminal has extremely basic capabilities */
2588 #define TERM_UNKNOWN	0x02	/* unknown terminal type */
2589 #define TERM_NOUP	0x04	/* terminal has no up capability */
2590 #define TERM_SHORT	0x08	/* terminal is < 3 lines high */
2591 #define TERM_NARROW	0x10	/* terminal is < 3 columns wide */
2592 
2593 /* interesting termcap strings */
2594 
2595 #define TCCLEARSCREEN   0
2596 #define TCLEFT          1
2597 #define TCMULTLEFT      2
2598 #define TCRIGHT         3
2599 #define TCMULTRIGHT     4
2600 #define TCUP            5
2601 #define TCMULTUP        6
2602 #define TCDOWN          7
2603 #define TCMULTDOWN      8
2604 #define TCDEL           9
2605 #define TCMULTDEL      10
2606 #define TCINS          11
2607 #define TCMULTINS      12
2608 #define TCCLEAREOD     13
2609 #define TCCLEAREOL     14
2610 #define TCINSLINE      15
2611 #define TCDELLINE      16
2612 #define TCNEXTTAB      17
2613 #define TCBOLDFACEBEG  18
2614 #define TCSTANDOUTBEG  19
2615 #define TCUNDERLINEBEG 20
2616 #define TCALLATTRSOFF  21
2617 #define TCSTANDOUTEND  22
2618 #define TCUNDERLINEEND 23
2619 #define TCHORIZPOS     24
2620 #define TCUPCURSOR     25
2621 #define TCDOWNCURSOR   26
2622 #define TCLEFTCURSOR   27
2623 #define TCRIGHTCURSOR  28
2624 #define TCSAVECURSOR   29
2625 #define TCRESTRCURSOR  30
2626 #define TCBACKSPACE    31
2627 #define TCFGCOLOUR     32
2628 #define TCBGCOLOUR     33
2629 #define TC_COUNT       34
2630 
2631 #define tccan(X) (tclen[X])
2632 
2633 /*
2634  * Text attributes for displaying in ZLE
2635  */
2636 
2637 #ifdef HAVE_STDINT_H
2638   typedef uint64_t zattr;
2639 #else
2640   typedef zulong zattr;
2641 #endif
2642 
2643 #define TXTBOLDFACE   0x0001
2644 #define TXTSTANDOUT   0x0002
2645 #define TXTUNDERLINE  0x0004
2646 #define TXTFGCOLOUR   0x0008
2647 #define TXTBGCOLOUR   0x0010
2648 
2649 #define TXT_ATTR_ON_MASK   0x001F
2650 
2651 #define txtisset(X)  (txtattrmask & (X))
2652 #define txtset(X)    (txtattrmask |= (X))
2653 #define txtunset(X)  (txtattrmask &= ~(X))
2654 
2655 #define TXTNOBOLDFACE	0x0020
2656 #define TXTNOSTANDOUT	0x0040
2657 #define TXTNOUNDERLINE	0x0080
2658 #define TXTNOFGCOLOUR	0x0100
2659 #define TXTNOBGCOLOUR	0x0200
2660 
2661 #define TXT_ATTR_OFF_MASK  0x03E0
2662 /* Bits to shift off right to get on */
2663 #define TXT_ATTR_OFF_ON_SHIFT 5
2664 #define TXT_ATTR_OFF_FROM_ON(attr)	\
2665     (((attr) & TXT_ATTR_ON_MASK) << TXT_ATTR_OFF_ON_SHIFT)
2666 #define TXT_ATTR_ON_FROM_OFF(attr)	\
2667     (((attr) & TXT_ATTR_OFF_MASK) >> TXT_ATTR_OFF_ON_SHIFT)
2668 /*
2669  * Indicates to zle_refresh.c that the character entry is an
2670  * index into the list of multiword symbols.
2671  */
2672 #define TXT_MULTIWORD_MASK  0x0400
2673 
2674 /* used when, e.g an invalid colour is specified */
2675 #define TXT_ERROR 0x0800
2676 
2677 /* Mask for colour to use in foreground */
2678 #define TXT_ATTR_FG_COL_MASK     0x000000FFFFFF0000
2679 /* Bits to shift the foreground colour */
2680 #define TXT_ATTR_FG_COL_SHIFT    (16)
2681 /* Mask for colour to use in background */
2682 #define TXT_ATTR_BG_COL_MASK     0xFFFFFF0000000000
2683 /* Bits to shift the background colour */
2684 #define TXT_ATTR_BG_COL_SHIFT    (40)
2685 
2686 /* Flag to use termcap AF sequence to set colour, if available */
2687 #define TXT_ATTR_FG_TERMCAP      0x1000
2688 /* Flag to use termcap AB sequence to set colour, if available */
2689 #define TXT_ATTR_BG_TERMCAP      0x2000
2690 
2691 /* Flag to indicate that foreground is a 24-bit colour */
2692 #define TXT_ATTR_FG_24BIT        0x4000
2693 /* Flag to indicate that background is a 24-bit colour */
2694 #define TXT_ATTR_BG_24BIT        0x8000
2695 
2696 /* Things to turn on, including values for the colour elements */
2697 #define TXT_ATTR_ON_VALUES_MASK	\
2698     (TXT_ATTR_ON_MASK|TXT_ATTR_FG_COL_MASK|TXT_ATTR_BG_COL_MASK|\
2699      TXT_ATTR_FG_TERMCAP|TXT_ATTR_BG_TERMCAP|\
2700      TXT_ATTR_FG_24BIT|TXT_ATTR_BG_24BIT)
2701 
2702 /* Mask out everything to do with setting a foreground colour */
2703 #define TXT_ATTR_FG_ON_MASK \
2704     (TXTFGCOLOUR|TXT_ATTR_FG_COL_MASK|TXT_ATTR_FG_TERMCAP|TXT_ATTR_FG_24BIT)
2705 
2706 /* Mask out everything to do with setting a background colour */
2707 #define TXT_ATTR_BG_ON_MASK \
2708     (TXTBGCOLOUR|TXT_ATTR_BG_COL_MASK|TXT_ATTR_BG_TERMCAP|TXT_ATTR_BG_24BIT)
2709 
2710 /* Mask out everything to do with activating colours */
2711 #define TXT_ATTR_COLOUR_ON_MASK			\
2712     (TXT_ATTR_FG_ON_MASK|TXT_ATTR_BG_ON_MASK)
2713 
2714 #define txtchangeisset(T,X)	((T) & (X))
2715 #define txtchangeget(T,A)	(((T) & A ## _MASK) >> A ## _SHIFT)
2716 #define txtchangeset(T, X, Y)	((void)(T && (*T &= ~(Y), *T |= (X))))
2717 
2718 /*
2719  * For outputting sequences to change colour: specify foreground
2720  * or background.
2721  */
2722 #define COL_SEQ_FG	(0)
2723 #define COL_SEQ_BG	(1)
2724 #define COL_SEQ_COUNT	(2)
2725 
2726 struct color_rgb {
2727     unsigned int red, green, blue;
2728 };
2729 
2730 typedef struct color_rgb *Color_rgb;
2731 
2732 /*
2733  * Flags to testcap() and set_colour_attribute (which currently only
2734  * handles TSC_PROMPT).
2735  */
2736 enum {
2737     /* Raw output: use stdout rather than shout */
2738     TSC_RAW = 0x0001,
2739     /* Output to current prompt buffer: only used when assembling prompt */
2740     TSC_PROMPT = 0x0002,
2741     /* Mask to get the output mode */
2742     TSC_OUTPUT_MASK = 0x0003,
2743     /* Change needs reset of other attributes */
2744     TSC_DIRTY = 0x0004
2745 };
2746 
2747 /****************************************/
2748 /* Definitions for the %_ prompt escape */
2749 /****************************************/
2750 
2751 #define CMDSTACKSZ 256
2752 
2753 #define CS_FOR          0
2754 #define CS_WHILE        1
2755 #define CS_REPEAT       2
2756 #define CS_SELECT       3
2757 #define CS_UNTIL        4
2758 #define CS_IF           5
2759 #define CS_IFTHEN       6
2760 #define CS_ELSE         7
2761 #define CS_ELIF         8
2762 #define CS_MATH         9
2763 #define CS_COND        10
2764 #define CS_CMDOR       11
2765 #define CS_CMDAND      12
2766 #define CS_PIPE        13
2767 #define CS_ERRPIPE     14
2768 #define CS_FOREACH     15
2769 #define CS_CASE        16
2770 #define CS_FUNCDEF     17
2771 #define CS_SUBSH       18
2772 #define CS_CURSH       19
2773 #define CS_ARRAY       20
2774 #define CS_QUOTE       21
2775 #define CS_DQUOTE      22
2776 #define CS_BQUOTE      23
2777 #define CS_CMDSUBST    24
2778 #define CS_MATHSUBST   25
2779 #define CS_ELIFTHEN    26
2780 #define CS_HEREDOC     27
2781 #define CS_HEREDOCD    28
2782 #define CS_BRACE       29
2783 #define CS_BRACEPAR    30
2784 #define CS_ALWAYS      31
2785 
2786 /* Increment as necessary */
2787 #define CS_COUNT       32
2788 
2789 /*********************
2790  * Memory management *
2791  *********************/
2792 
2793 /*
2794  * A Heapid is a type for identifying, uniquely up to the point where
2795  * the count of new identifiers wraps. all heaps that are or
2796  * (importantly) have been valid.  Each valid heap is given an
2797  * identifier, and every time we push a heap we save the old identifier
2798  * and give the heap a new identifier so that when the heap is popped
2799  * or freed we can spot anything using invalid memory from the popped
2800  * heap.
2801  *
2802  * We could make this unsigned long long if we wanted a big range.
2803  */
2804 typedef unsigned int Heapid;
2805 
2806 #ifdef ZSH_HEAP_DEBUG
2807 
2808 /* printf format specifier corresponding to Heapid */
2809 #define HEAPID_FMT	"%x"
2810 
2811 /* Marker that memory is permanently allocated */
2812 #define HEAPID_PERMANENT (UINT_MAX)
2813 
2814 /*
2815  * Heap debug verbosity.
2816  * Bits to be 'or'ed into the variable also called heap_debug_verbosity.
2817  */
2818 enum heap_debug_verbosity {
2819     /* Report when we push a heap */
2820     HDV_PUSH = 0x01,
2821     /* Report when we pop a heap */
2822     HDV_POP = 0x02,
2823     /* Report when we create a new heap from which to allocate */
2824     HDV_CREATE = 0x04,
2825     /* Report every time we free a complete heap */
2826     HDV_FREE = 0x08,
2827     /* Report when we temporarily install a new set of heaps */
2828     HDV_NEW = 0x10,
2829     /* Report when we restore an old set of heaps */
2830     HDV_OLD = 0x20,
2831     /* Report when we temporarily switch heaps */
2832     HDV_SWITCH = 0x40,
2833     /*
2834      * Report every time we allocate memory from the heap.
2835      * This is very verbose, and arguably not very useful: we
2836      * would expect to allocate memory from a heap we create.
2837      * For much debugging heap_debug_verbosity = 0x7f should be sufficient.
2838      */
2839     HDV_ALLOC = 0x80
2840 };
2841 
2842 #define HEAP_ERROR(heap_id)			\
2843     fprintf(stderr, "%s:%d: HEAP DEBUG: invalid heap: " HEAPID_FMT ".\n", \
2844 	    __FILE__, __LINE__, heap_id)
2845 #endif
2846 
2847 /* heappush saves the current heap state using this structure */
2848 
2849 struct heapstack {
2850     struct heapstack *next;	/* next one in list for this heap */
2851     size_t used;
2852 #ifdef ZSH_HEAP_DEBUG
2853     Heapid heap_id;
2854 #endif
2855 };
2856 
2857 /* A zsh heap. */
2858 
2859 struct heap {
2860     struct heap *next;		/* next one                                  */
2861     size_t size;		/* size of heap                              */
2862     size_t used;		/* bytes used from the heap                  */
2863     struct heapstack *sp;	/* used by pushheap() to save the value used */
2864 
2865 #ifdef ZSH_HEAP_DEBUG
2866     unsigned int heap_id;
2867 #endif
2868 
2869 /* Uncomment the following if the struct needs padding to 64-bit size. */
2870 /* Make sure sizeof(heap) is a multiple of 8
2871 #if defined(PAD_64_BIT) && !defined(__GNUC__)
2872     size_t dummy;
2873 #endif
2874 */
2875 #define arena(X)	((char *) (X) + sizeof(struct heap))
2876 }
2877 #if defined(PAD_64_BIT) && defined(__GNUC__)
2878   __attribute__ ((aligned (8)))
2879 #endif
2880 ;
2881 
2882 # define NEWHEAPS(h)    do { Heap _switch_oldheaps = h = new_heaps(); do
2883 # define OLDHEAPS       while (0); old_heaps(_switch_oldheaps); } while (0);
2884 
2885 # define SWITCHHEAPS(o, h)  do { o = switch_heaps(h); do
2886 # define SWITCHBACKHEAPS(o) while (0); switch_heaps(o); } while (0);
2887 
2888 /****************/
2889 /* Debug macros */
2890 /****************/
2891 
2892 #ifdef DEBUG
2893 #define STRINGIFY_LITERAL(x)	# x
2894 #define STRINGIFY(x)		STRINGIFY_LITERAL(x)
2895 #define ERRMSG(x)		(__FILE__ ":" STRINGIFY(__LINE__) ": " x)
2896 # define DPUTS(X,Y) if (!(X)) {;} else dputs(ERRMSG(Y))
2897 # define DPUTS1(X,Y,Z1) if (!(X)) {;} else dputs(ERRMSG(Y), Z1)
2898 # define DPUTS2(X,Y,Z1,Z2) if (!(X)) {;} else dputs(ERRMSG(Y), Z1, Z2)
2899 # define DPUTS3(X,Y,Z1,Z2,Z3) if (!(X)) {;} else dputs(ERRMSG(Y), Z1, Z2, Z3)
2900 #else
2901 # define DPUTS(X,Y)
2902 # define DPUTS1(X,Y,Z1)
2903 # define DPUTS2(X,Y,Z1,Z2)
2904 # define DPUTS3(X,Y,Z1,Z2,Z3)
2905 #endif
2906 
2907 /**************************/
2908 /* Signal handling macros */
2909 /**************************/
2910 
2911 /* These used in the sigtrapped[] array */
2912 
2913 #define ZSIG_TRAPPED	(1<<0)	/* Signal is trapped */
2914 #define ZSIG_IGNORED	(1<<1)	/* Signal is ignored */
2915 #define ZSIG_FUNC	(1<<2)	/* Trap is a function, not an eval list */
2916 /* Mask to get the above flags */
2917 #define ZSIG_MASK	(ZSIG_TRAPPED|ZSIG_IGNORED|ZSIG_FUNC)
2918 /* No. of bits to shift local level when storing in sigtrapped */
2919 #define ZSIG_ALIAS	(1<<3)  /* Trap is stored under an alias */
2920 #define ZSIG_SHIFT	4
2921 
2922 /*
2923  * State of traps, stored in trap_state.
2924  */
2925 enum trap_state {
2926     /* Traps are not active; trap_return is not useful. */
2927     TRAP_STATE_INACTIVE,
2928     /*
2929      * Traps are set but haven't triggered; trap_return gives
2930      * minus function depth.
2931      */
2932     TRAP_STATE_PRIMED,
2933     /*
2934      * Trap has triggered to force a return; trap_return givens
2935      * return value.
2936      */
2937     TRAP_STATE_FORCE_RETURN
2938 };
2939 
2940 #define IN_EVAL_TRAP() \
2941     (intrap && !trapisfunc && traplocallevel == locallevel)
2942 
2943 /*
2944  * Bits in the errflag variable.
2945  */
2946 enum errflag_bits {
2947     /*
2948      * Standard internal error bit.
2949      */
2950     ERRFLAG_ERROR = 1,
2951     /*
2952      * User interrupt.
2953      */
2954     ERRFLAG_INT = 2,
2955     /*
2956      * Hard error --- return to top-level prompt in interactive
2957      * shell.  In non-interactive shell we'll typically already
2958      * have exited.  This is reset by "errflag = 0" in
2959      * loop(toplevel = 1, ...).
2960      */
2961     ERRFLAG_HARD = 4
2962 };
2963 
2964 /***********/
2965 /* Sorting */
2966 /***********/
2967 
2968 typedef int (*CompareFn) _((const void *, const void *));
2969 
2970 enum {
2971     SORTIT_ANYOLDHOW = 0,	/* Defaults */
2972     SORTIT_IGNORING_CASE = 1,
2973     SORTIT_NUMERICALLY = 2,
2974     SORTIT_BACKWARDS = 4,
2975     /*
2976      * Ignore backslashes that quote another character---which may
2977      * be another backslash; the second backslash is active.
2978      */
2979     SORTIT_IGNORING_BACKSLASHES = 8,
2980     /*
2981      * Ignored by strmetasort(); used by paramsubst() to indicate
2982      * there is some sorting to do.
2983      */
2984     SORTIT_SOMEHOW = 16,
2985 };
2986 
2987 /*
2988  * Element of array passed to qsort().
2989  */
2990 struct sortelt {
2991     /* The original string. */
2992     char *orig;
2993     /* The string used for comparison. */
2994     const char *cmp;
2995     /*
2996      * The length of the string if passed down to the sort algorithm.
2997      * Used to sort the lengths together with the strings.
2998      */
2999     int origlen;
3000     /*
3001      * The length of the string, if needed, else -1.
3002      * The length is only needed if there are embedded nulls.
3003      */
3004     int len;
3005 };
3006 
3007 typedef struct sortelt *SortElt;
3008 
3009 /*********************************************************/
3010 /* Structures to save and restore for individual modules */
3011 /*********************************************************/
3012 
3013 /* History */
3014 struct hist_stack {
3015     int histactive;
3016     int histdone;
3017     int stophist;
3018     int hlinesz;
3019     zlong defev;
3020     char *hline;
3021     char *hptr;
3022     short *chwords;
3023     int chwordlen;
3024     int chwordpos;
3025     int (*hgetc) _((void));
3026     void (*hungetc) _((int));
3027     void (*hwaddc) _((int));
3028     void (*hwbegin) _((int));
3029     void (*hwabort) _((void));
3030     void (*hwend) _((void));
3031     void (*addtoline) _((int));
3032     unsigned char *cstack;
3033     int csp;
3034     int hist_keep_comment;
3035 };
3036 
3037 /*
3038  * State of a lexical token buffer.
3039  *
3040  * It would be neater to include the pointer to the start of the buffer,
3041  * however the current code structure means that the standard instance
3042  * of this, tokstr, is visible in lots of places, so that's not
3043  * convenient.
3044  */
3045 
3046 struct lexbufstate {
3047     /*
3048      * Next character to be added.
3049      * Set to NULL when the buffer is to be visible from elsewhere.
3050      */
3051     char *ptr;
3052     /* Allocated buffer size */
3053     int siz;
3054     /* Length in use */
3055     int len;
3056 };
3057 
3058 /* Lexical analyser */
3059 struct lex_stack {
3060     int dbparens;
3061     int isfirstln;
3062     int isfirstch;
3063     int lexflags;
3064     enum lextok tok;
3065     char *tokstr;
3066     char *zshlextext;
3067     struct lexbufstate lexbuf;
3068     int lex_add_raw;
3069     char *tokstr_raw;
3070     struct lexbufstate lexbuf_raw;
3071     int lexstop;
3072     zlong toklineno;
3073 };
3074 
3075 /* Parser */
3076 struct parse_stack {
3077     struct heredocs *hdocs;
3078 
3079     int incmdpos;
3080     int aliasspaceflag;
3081     int incond;
3082     int inredir;
3083     int incasepat;
3084     int isnewlin;
3085     int infor;
3086     int inrepeat_;
3087     int intypeset;
3088 
3089     int eclen, ecused, ecnpats;
3090     Wordcode ecbuf;
3091     Eccstr ecstrs;
3092     int ecsoffs, ecssub, ecnfunc;
3093 };
3094 
3095 /************************/
3096 /* Flags to casemodifiy */
3097 /************************/
3098 
3099 enum {
3100     CASMOD_NONE,		/* dummy for tests */
3101     CASMOD_UPPER,
3102     CASMOD_LOWER,
3103     CASMOD_CAPS
3104 };
3105 
3106 /*******************************************/
3107 /* Flags to third argument of getkeystring */
3108 /*******************************************/
3109 
3110 /*
3111  * By default handles some subset of \-escapes.  The following bits
3112  * turn on extra features.
3113  */
3114 enum {
3115     /*
3116      * Handle octal where the first digit is non-zero e.g. \3, \33, \333
3117      * Otherwise \0333 etc. is handled, i.e. one of \0123 or \123 will
3118      * work, but not both.
3119      */
3120     GETKEY_OCTAL_ESC = (1 << 0),
3121     /*
3122      * Handle Emacs-like key sequences \C-x etc.
3123      * Also treat \E like \e and use backslashes to escape the
3124      * next character if not special, i.e. do all the things we
3125      * don't do with the echo builtin.
3126      */
3127     GETKEY_EMACS = (1 << 1),
3128     /* Handle ^X etc. */
3129     GETKEY_CTRL = (1 << 2),
3130     /* Handle \c (uses misc arg to getkeystring()) */
3131     GETKEY_BACKSLASH_C = (1 << 3),
3132     /* Do $'...' quoting (len arg to getkeystring() not used) */
3133     GETKEY_DOLLAR_QUOTE = (1 << 4),
3134     /* Handle \- (uses misc arg to getkeystring()) */
3135     GETKEY_BACKSLASH_MINUS = (1 << 5),
3136     /* Parse only one character (len arg to getkeystring() not used) */
3137     GETKEY_SINGLE_CHAR = (1 << 6),
3138     /*
3139      * If beyond offset in misc arg, add 1 to it for each character removed.
3140      * Yes, I know that doesn't seem to make much sense.
3141      * It's for use in completion, comprenez?
3142      */
3143     GETKEY_UPDATE_OFFSET = (1 << 7),
3144     /*
3145      * When replacing numeric escapes for printf format strings, % -> %%
3146      */
3147     GETKEY_PRINTF_PERCENT = (1 << 8)
3148 };
3149 
3150 /*
3151  * Standard combinations used within the shell.
3152  * Note GETKEYS_... instead of GETKEY_...: this is important in some cases.
3153  */
3154 /* echo builtin */
3155 #define GETKEYS_ECHO	(GETKEY_BACKSLASH_C)
3156 /* printf format string:  \123 -> S, \0123 -> NL 3, \045 -> %% */
3157 #define GETKEYS_PRINTF_FMT	\
3158         (GETKEY_OCTAL_ESC|GETKEY_BACKSLASH_C|GETKEY_PRINTF_PERCENT)
3159 /* printf argument:  \123 -> \123, \0123 -> S */
3160 #define GETKEYS_PRINTF_ARG	(GETKEY_BACKSLASH_C)
3161 /* Full print without -e */
3162 #define GETKEYS_PRINT	(GETKEY_OCTAL_ESC|GETKEY_BACKSLASH_C|GETKEY_EMACS)
3163 /* bindkey */
3164 #define GETKEYS_BINDKEY	(GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL)
3165 /* $'...' */
3166 #define GETKEYS_DOLLARS_QUOTE (GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_DOLLAR_QUOTE)
3167 /* Single character for math processing */
3168 #define GETKEYS_MATH	\
3169 	(GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL|GETKEY_SINGLE_CHAR)
3170 /* Used to process separators etc. with print-style escapes */
3171 #define GETKEYS_SEP	(GETKEY_OCTAL_ESC|GETKEY_EMACS)
3172 /* Used for suffix removal */
3173 #define GETKEYS_SUFFIX		\
3174 	(GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL|GETKEY_BACKSLASH_MINUS)
3175 
3176 /**********************************/
3177 /* Flags to third argument of zle */
3178 /**********************************/
3179 
3180 #define ZLRF_HISTORY	0x01	/* OK to access the history list */
3181 #define ZLRF_NOSETTY	0x02	/* Don't set tty before return */
3182 #define ZLRF_IGNOREEOF  0x04	/* Ignore an EOF from the keyboard */
3183 
3184 /***************************/
3185 /* Context of zleread call */
3186 /***************************/
3187 
3188 enum {
3189     ZLCON_LINE_START,		/* Command line at PS1 */
3190     ZLCON_LINE_CONT,		/* Command line at PS2 */
3191     ZLCON_SELECT,		/* Select loop */
3192     ZLCON_VARED			/* Vared command */
3193 };
3194 
3195 /****************/
3196 /* Entry points */
3197 /****************/
3198 
3199 /* compctl entry point pointers */
3200 
3201 typedef int (*CompctlReadFn) _((char *, char **, Options, char *));
3202 
3203 /* ZLE entry point pointer */
3204 
3205 typedef char * (*ZleEntryPoint)(int cmd, va_list ap);
3206 
3207 /* Commands to pass to entry point */
3208 
3209 enum {
3210     ZLE_CMD_GET_LINE,
3211     ZLE_CMD_READ,
3212     ZLE_CMD_ADD_TO_LINE,
3213     ZLE_CMD_TRASH,
3214     ZLE_CMD_RESET_PROMPT,
3215     ZLE_CMD_REFRESH,
3216     ZLE_CMD_SET_KEYMAP,
3217     ZLE_CMD_GET_KEY,
3218     ZLE_CMD_SET_HIST_LINE
3219 };
3220 
3221 /***************************************/
3222 /* Hooks in core.                      */
3223 /***************************************/
3224 
3225 /* The type of zexit()'s second parameter, which see. */
3226 enum zexit_t {
3227     /* This isn't a bitfield. The values are here just for explicitness. */
3228     ZEXIT_NORMAL = 0,
3229     ZEXIT_SIGNAL = 1,
3230     ZEXIT_DEFERRED = 2
3231 };
3232 
3233 #define EXITHOOK       (zshhooks + 0)
3234 #define BEFORETRAPHOOK (zshhooks + 1)
3235 #define AFTERTRAPHOOK  (zshhooks + 2)
3236 #define GETCOLORATTR   (zshhooks + 3)
3237 
3238 #ifdef MULTIBYTE_SUPPORT
3239 /* Final argument to mb_niceformat() */
3240 enum {
3241     NICEFLAG_HEAP = 1,		/* Heap allocation where needed */
3242     NICEFLAG_QUOTE = 2,		/* Result will appear in $'...' */
3243     NICEFLAG_NODUP = 4,         /* Leave allocated */
3244 };
3245 
3246 /* Metafied input */
3247 #define nicezputs(str, outs)	(void)mb_niceformat((str), (outs), NULL, 0)
3248 #define MB_METACHARINIT()	mb_charinit()
3249 typedef wint_t convchar_t;
3250 #define MB_METACHARLENCONV(str, cp)	mb_metacharlenconv((str), (cp))
3251 #define MB_METACHARLEN(str)	mb_metacharlenconv(str, NULL)
3252 #define MB_METASTRLEN(str)	mb_metastrlenend(str, 0, NULL)
3253 #define MB_METASTRWIDTH(str)	mb_metastrlenend(str, 1, NULL)
3254 #define MB_METASTRLEN2(str, widthp)	mb_metastrlenend(str, widthp, NULL)
3255 #define MB_METASTRLEN2END(str, widthp, eptr)	\
3256     mb_metastrlenend(str, widthp, eptr)
3257 
3258 /* Unmetafined input */
3259 #define MB_CHARINIT()		mb_charinit()
3260 #define MB_CHARLENCONV(str, len, cp)	mb_charlenconv((str), (len), (cp))
3261 #define MB_CHARLEN(str, len)	mb_charlenconv((str), (len), NULL)
3262 
3263 /*
3264  * We replace broken implementations with one that uses Unicode
3265  * characters directly as wide characters.  In principle this is only
3266  * likely to work if __STDC_ISO_10646__ is defined, since that's pretty
3267  * much what the definition tells us.  However, we happen to know this
3268  * works on MacOS which doesn't define that.
3269  */
3270 #ifdef ENABLE_UNICODE9
3271 #define WCWIDTH(wc)	u9_wcwidth(wc)
3272 #else
3273 #define WCWIDTH(wc)	wcwidth(wc)
3274 #endif
3275 /*
3276  * Note WCWIDTH_WINT() takes wint_t, typically as a convchar_t.
3277  * It's written to use the wint_t from mb_metacharlenconv() without
3278  * further tests.
3279  *
3280  * This version has a non-multibyte definition that simply returns
3281  * 1.  We never expose WCWIDTH() in the non-multibyte world since
3282  * it's just a proxy for wcwidth() itself.
3283  */
3284 #define WCWIDTH_WINT(wc)	zwcwidth(wc)
3285 
3286 #define MB_INCOMPLETE	((size_t)-2)
3287 #define MB_INVALID	((size_t)-1)
3288 
3289 /*
3290  * MB_CUR_MAX is the maximum number of bytes that a single wide
3291  * character will convert into.  We use it to keep strings
3292  * sufficiently long.  It should always be defined, but if it isn't
3293  * just assume we are using Unicode which requires 6 characters.
3294  * (Note that it's not necessarily defined to a constant.)
3295  */
3296 #ifndef MB_CUR_MAX
3297 #define MB_CUR_MAX 6
3298 #endif
3299 
3300 /* Convert character or string to wide character or string */
3301 #define ZWC(c)	L ## c
3302 #define ZWS(s)	L ## s
3303 
3304 /*
3305  * Test for a combining character.
3306  *
3307  * wc is assumed to be a wchar_t (i.e. we don't need zwcwidth).
3308  *
3309  * Pedantic note: in Unicode, a combining character need not be
3310  * zero length.  However, we are concerned here about display;
3311  * we simply need to know whether the character will be displayed
3312  * on top of another one.  We use "combining character" in this
3313  * sense throughout the shell.  I am not aware of a way of
3314  * detecting the Unicode trait in standard libraries.
3315  */
3316 #define IS_COMBINING(wc)	(wc != 0 && WCWIDTH(wc) == 0)
3317 /*
3318  * Test for the base of a combining character.
3319  *
3320  * We assume a combining character can be successfully displayed with
3321  * any non-space printable character, which is what a graphic character
3322  * is, as long as it has non-zero width.  We need to avoid all forms of
3323  * space because the shell will split words on any whitespace.
3324  */
3325 #define IS_BASECHAR(wc)		(iswgraph(wc) && WCWIDTH(wc) > 0)
3326 
3327 #else /* not MULTIBYTE_SUPPORT */
3328 
3329 #define MB_METACHARINIT()
3330 typedef int convchar_t;
3331 #define MB_METACHARLENCONV(str, cp)	metacharlenconv((str), (cp))
3332 #define MB_METACHARLEN(str)	(*(str) == Meta ? 2 : 1)
3333 #define MB_METASTRLEN(str)	ztrlen(str)
3334 #define MB_METASTRWIDTH(str)	ztrlen(str)
3335 #define MB_METASTRLEN2(str, widthp)	ztrlen(str)
3336 #define MB_METASTRLEN2END(str, widthp, eptr)	ztrlenend(str, eptr)
3337 
3338 #define MB_CHARINIT()
3339 #define MB_CHARLENCONV(str, len, cp) charlenconv((str), (len), (cp))
3340 #define MB_CHARLEN(str, len) ((len) ? 1 : 0)
3341 
3342 #define WCWIDTH_WINT(c)	(1)
3343 
3344 /* Leave character or string as is. */
3345 #define ZWC(c)	c
3346 #define ZWS(s)	s
3347 
3348 #endif /* MULTIBYTE_SUPPORT */
3349