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