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