sound: Create the first /dev/dsp* links
[dragonfly.git] / bin / sh / parser.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)parser.c 8.7 (Berkeley) 5/16/95
33  * $FreeBSD: head/bin/sh/parser.c 253659 2013-07-25 20:50:35Z jilles $
34  */
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39
40 #include "shell.h"
41 #include "parser.h"
42 #include "nodes.h"
43 #include "expand.h"     /* defines rmescapes() */
44 #include "syntax.h"
45 #include "options.h"
46 #include "input.h"
47 #include "output.h"
48 #include "var.h"
49 #include "error.h"
50 #include "memalloc.h"
51 #include "mystring.h"
52 #include "alias.h"
53 #include "show.h"
54 #include "eval.h"
55 #include "exec.h"       /* to check for special builtins */
56 #ifndef NO_HISTORY
57 #include "myhistedit.h"
58 #endif
59
60 /*
61  * Shell command parser.
62  */
63
64 #define EOFMARKLEN      79
65 #define PROMPTLEN       128
66
67 /* values of checkkwd variable */
68 #define CHKALIAS        0x1
69 #define CHKKWD          0x2
70 #define CHKNL           0x4
71
72 /* values returned by readtoken */
73 #include "token.h"
74
75
76
77 struct heredoc {
78         struct heredoc *next;   /* next here document in list */
79         union node *here;               /* redirection node */
80         char *eofmark;          /* string indicating end of input */
81         int striptabs;          /* if set, strip leading tabs */
82 };
83
84 struct parser_temp {
85         struct parser_temp *next;
86         void *data;
87 };
88
89
90 static struct heredoc *heredoclist;     /* list of here documents to read */
91 static int doprompt;            /* if set, prompt the user */
92 static int needprompt;          /* true if interactive and at start of line */
93 static int lasttoken;           /* last token read */
94 int tokpushback;                /* last token pushed back */
95 static char *wordtext;          /* text of last word returned by readtoken */
96 static int checkkwd;
97 static struct nodelist *backquotelist;
98 static union node *redirnode;
99 static struct heredoc *heredoc;
100 static int quoteflag;           /* set if (part of) last token was quoted */
101 static int startlinno;          /* line # where last token started */
102 static int funclinno;           /* line # where the current function started */
103 static struct parser_temp *parser_temp;
104
105
106 static union node *list(int, int);
107 static union node *andor(void);
108 static union node *pipeline(void);
109 static union node *command(void);
110 static union node *simplecmd(union node **, union node *);
111 static union node *makename(void);
112 static void parsefname(void);
113 static void parseheredoc(void);
114 static int peektoken(void);
115 static int readtoken(void);
116 static int xxreadtoken(void);
117 static int readtoken1(int, const char *, const char *, int);
118 static int noexpand(char *);
119 static void synexpect(int) __dead2;
120 static void synerror(const char *) __dead2;
121 static void setprompt(int);
122
123
124 static void *
125 parser_temp_alloc(size_t len)
126 {
127         struct parser_temp *t;
128
129         INTOFF;
130         t = ckmalloc(sizeof(*t));
131         t->data = NULL;
132         t->next = parser_temp;
133         parser_temp = t;
134         t->data = ckmalloc(len);
135         INTON;
136         return t->data;
137 }
138
139
140 static void *
141 parser_temp_realloc(void *ptr, size_t len)
142 {
143         struct parser_temp *t;
144
145         INTOFF;
146         t = parser_temp;
147         if (ptr != t->data)
148                 error("bug: parser_temp_realloc misused");
149         t->data = ckrealloc(t->data, len);
150         INTON;
151         return t->data;
152 }
153
154
155 static void
156 parser_temp_free_upto(void *ptr)
157 {
158         struct parser_temp *t;
159         int done = 0;
160
161         INTOFF;
162         while (parser_temp != NULL && !done) {
163                 t = parser_temp;
164                 parser_temp = t->next;
165                 done = t->data == ptr;
166                 ckfree(t->data);
167                 ckfree(t);
168         }
169         INTON;
170         if (!done)
171                 error("bug: parser_temp_free_upto misused");
172 }
173
174
175 static void
176 parser_temp_free_all(void)
177 {
178         struct parser_temp *t;
179
180         INTOFF;
181         while (parser_temp != NULL) {
182                 t = parser_temp;
183                 parser_temp = t->next;
184                 ckfree(t->data);
185                 ckfree(t);
186         }
187         INTON;
188 }
189
190
191 /*
192  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
193  * valid parse tree indicating a blank line.)
194  */
195
196 union node *
197 parsecmd(int interact)
198 {
199         int t;
200
201         /* This assumes the parser is not re-entered,
202          * which could happen if we add command substitution on PS1/PS2.
203          */
204         parser_temp_free_all();
205         heredoclist = NULL;
206
207         tokpushback = 0;
208         doprompt = interact;
209         if (doprompt)
210                 setprompt(1);
211         else
212                 setprompt(0);
213         needprompt = 0;
214         t = readtoken();
215         if (t == TEOF)
216                 return NEOF;
217         if (t == TNL)
218                 return NULL;
219         tokpushback++;
220         return list(1, 1);
221 }
222
223
224 static union node *
225 list(int nlflag, int erflag)
226 {
227         union node *ntop, *n1, *n2, *n3;
228         int tok;
229
230         checkkwd = CHKNL | CHKKWD | CHKALIAS;
231         if (!nlflag && !erflag && tokendlist[peektoken()])
232                 return NULL;
233         ntop = n1 = NULL;
234         for (;;) {
235                 n2 = andor();
236                 tok = readtoken();
237                 if (tok == TBACKGND) {
238                         if (n2 != NULL && n2->type == NPIPE) {
239                                 n2->npipe.backgnd = 1;
240                         } else if (n2 != NULL && n2->type == NREDIR) {
241                                 n2->type = NBACKGND;
242                         } else {
243                                 n3 = (union node *)stalloc(sizeof (struct nredir));
244                                 n3->type = NBACKGND;
245                                 n3->nredir.n = n2;
246                                 n3->nredir.redirect = NULL;
247                                 n2 = n3;
248                         }
249                 }
250                 if (ntop == NULL)
251                         ntop = n2;
252                 else if (n1 == NULL) {
253                         n1 = (union node *)stalloc(sizeof (struct nbinary));
254                         n1->type = NSEMI;
255                         n1->nbinary.ch1 = ntop;
256                         n1->nbinary.ch2 = n2;
257                         ntop = n1;
258                 }
259                 else {
260                         n3 = (union node *)stalloc(sizeof (struct nbinary));
261                         n3->type = NSEMI;
262                         n3->nbinary.ch1 = n1->nbinary.ch2;
263                         n3->nbinary.ch2 = n2;
264                         n1->nbinary.ch2 = n3;
265                         n1 = n3;
266                 }
267                 switch (tok) {
268                 case TBACKGND:
269                 case TSEMI:
270                         tok = readtoken();
271                         /* FALLTHROUGH */
272                 case TNL:
273                         if (tok == TNL) {
274                                 parseheredoc();
275                                 if (nlflag)
276                                         return ntop;
277                         } else if (tok == TEOF && nlflag) {
278                                 parseheredoc();
279                                 return ntop;
280                         } else {
281                                 tokpushback++;
282                         }
283                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
284                         if (!nlflag && (erflag ? peektoken() == TEOF :
285                             tokendlist[peektoken()]))
286                                 return ntop;
287                         break;
288                 case TEOF:
289                         if (heredoclist)
290                                 parseheredoc();
291                         else
292                                 pungetc();              /* push back EOF on input */
293                         return ntop;
294                 default:
295                         if (nlflag || erflag)
296                                 synexpect(-1);
297                         tokpushback++;
298                         return ntop;
299                 }
300         }
301 }
302
303
304
305 static union node *
306 andor(void)
307 {
308         union node *n1, *n2, *n3;
309         int t;
310
311         n1 = pipeline();
312         for (;;) {
313                 if ((t = readtoken()) == TAND) {
314                         t = NAND;
315                 } else if (t == TOR) {
316                         t = NOR;
317                 } else {
318                         tokpushback++;
319                         return n1;
320                 }
321                 n2 = pipeline();
322                 n3 = (union node *)stalloc(sizeof (struct nbinary));
323                 n3->type = t;
324                 n3->nbinary.ch1 = n1;
325                 n3->nbinary.ch2 = n2;
326                 n1 = n3;
327         }
328 }
329
330
331
332 static union node *
333 pipeline(void)
334 {
335         union node *n1, *n2, *pipenode;
336         struct nodelist *lp, *prev;
337         int negate, t;
338
339         negate = 0;
340         checkkwd = CHKNL | CHKKWD | CHKALIAS;
341         TRACE(("pipeline: entered\n"));
342         while (readtoken() == TNOT)
343                 negate = !negate;
344         tokpushback++;
345         n1 = command();
346         if (readtoken() == TPIPE) {
347                 pipenode = (union node *)stalloc(sizeof (struct npipe));
348                 pipenode->type = NPIPE;
349                 pipenode->npipe.backgnd = 0;
350                 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
351                 pipenode->npipe.cmdlist = lp;
352                 lp->n = n1;
353                 do {
354                         prev = lp;
355                         lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
356                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
357                         t = readtoken();
358                         tokpushback++;
359                         if (t == TNOT)
360                                 lp->n = pipeline();
361                         else
362                                 lp->n = command();
363                         prev->next = lp;
364                 } while (readtoken() == TPIPE);
365                 lp->next = NULL;
366                 n1 = pipenode;
367         }
368         tokpushback++;
369         if (negate) {
370                 n2 = (union node *)stalloc(sizeof (struct nnot));
371                 n2->type = NNOT;
372                 n2->nnot.com = n1;
373                 return n2;
374         } else
375                 return n1;
376 }
377
378
379
380 static union node *
381 command(void)
382 {
383         union node *n1, *n2;
384         union node *ap, **app;
385         union node *cp, **cpp;
386         union node *redir, **rpp;
387         int t;
388         int is_subshell;
389
390         checkkwd = CHKNL | CHKKWD | CHKALIAS;
391         is_subshell = 0;
392         redir = NULL;
393         n1 = NULL;
394         rpp = &redir;
395
396         /* Check for redirection which may precede command */
397         while (readtoken() == TREDIR) {
398                 *rpp = n2 = redirnode;
399                 rpp = &n2->nfile.next;
400                 parsefname();
401         }
402         tokpushback++;
403
404         switch (readtoken()) {
405         case TIF:
406                 n1 = (union node *)stalloc(sizeof (struct nif));
407                 n1->type = NIF;
408                 if ((n1->nif.test = list(0, 0)) == NULL)
409                         synexpect(-1);
410                 if (readtoken() != TTHEN)
411                         synexpect(TTHEN);
412                 n1->nif.ifpart = list(0, 0);
413                 n2 = n1;
414                 while (readtoken() == TELIF) {
415                         n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
416                         n2 = n2->nif.elsepart;
417                         n2->type = NIF;
418                         if ((n2->nif.test = list(0, 0)) == NULL)
419                                 synexpect(-1);
420                         if (readtoken() != TTHEN)
421                                 synexpect(TTHEN);
422                         n2->nif.ifpart = list(0, 0);
423                 }
424                 if (lasttoken == TELSE)
425                         n2->nif.elsepart = list(0, 0);
426                 else {
427                         n2->nif.elsepart = NULL;
428                         tokpushback++;
429                 }
430                 if (readtoken() != TFI)
431                         synexpect(TFI);
432                 checkkwd = CHKKWD | CHKALIAS;
433                 break;
434         case TWHILE:
435         case TUNTIL: {
436                 int got;
437                 n1 = (union node *)stalloc(sizeof (struct nbinary));
438                 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
439                 if ((n1->nbinary.ch1 = list(0, 0)) == NULL)
440                         synexpect(-1);
441                 if ((got=readtoken()) != TDO) {
442 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
443                         synexpect(TDO);
444                 }
445                 n1->nbinary.ch2 = list(0, 0);
446                 if (readtoken() != TDONE)
447                         synexpect(TDONE);
448                 checkkwd = CHKKWD | CHKALIAS;
449                 break;
450         }
451         case TFOR:
452                 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
453                         synerror("Bad for loop variable");
454                 n1 = (union node *)stalloc(sizeof (struct nfor));
455                 n1->type = NFOR;
456                 n1->nfor.var = wordtext;
457                 while (readtoken() == TNL)
458                         ;
459                 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
460                         app = &ap;
461                         while (readtoken() == TWORD) {
462                                 n2 = (union node *)stalloc(sizeof (struct narg));
463                                 n2->type = NARG;
464                                 n2->narg.text = wordtext;
465                                 n2->narg.backquote = backquotelist;
466                                 *app = n2;
467                                 app = &n2->narg.next;
468                         }
469                         *app = NULL;
470                         n1->nfor.args = ap;
471                         if (lasttoken != TNL && lasttoken != TSEMI)
472                                 synexpect(-1);
473                 } else {
474                         static char argvars[5] = {
475                                 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
476                         };
477                         n2 = (union node *)stalloc(sizeof (struct narg));
478                         n2->type = NARG;
479                         n2->narg.text = argvars;
480                         n2->narg.backquote = NULL;
481                         n2->narg.next = NULL;
482                         n1->nfor.args = n2;
483                         /*
484                          * Newline or semicolon here is optional (but note
485                          * that the original Bourne shell only allowed NL).
486                          */
487                         if (lasttoken != TNL && lasttoken != TSEMI)
488                                 tokpushback++;
489                 }
490                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
491                 if ((t = readtoken()) == TDO)
492                         t = TDONE;
493                 else if (t == TBEGIN)
494                         t = TEND;
495                 else
496                         synexpect(-1);
497                 n1->nfor.body = list(0, 0);
498                 if (readtoken() != t)
499                         synexpect(t);
500                 checkkwd = CHKKWD | CHKALIAS;
501                 break;
502         case TCASE:
503                 n1 = (union node *)stalloc(sizeof (struct ncase));
504                 n1->type = NCASE;
505                 if (readtoken() != TWORD)
506                         synexpect(TWORD);
507                 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
508                 n2->type = NARG;
509                 n2->narg.text = wordtext;
510                 n2->narg.backquote = backquotelist;
511                 n2->narg.next = NULL;
512                 while (readtoken() == TNL);
513                 if (lasttoken != TWORD || ! equal(wordtext, "in"))
514                         synerror("expecting \"in\"");
515                 cpp = &n1->ncase.cases;
516                 checkkwd = CHKNL | CHKKWD, readtoken();
517                 while (lasttoken != TESAC) {
518                         *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
519                         cp->type = NCLIST;
520                         app = &cp->nclist.pattern;
521                         if (lasttoken == TLP)
522                                 readtoken();
523                         for (;;) {
524                                 *app = ap = (union node *)stalloc(sizeof (struct narg));
525                                 ap->type = NARG;
526                                 ap->narg.text = wordtext;
527                                 ap->narg.backquote = backquotelist;
528                                 checkkwd = CHKNL | CHKKWD;
529                                 if (readtoken() != TPIPE)
530                                         break;
531                                 app = &ap->narg.next;
532                                 readtoken();
533                         }
534                         ap->narg.next = NULL;
535                         if (lasttoken != TRP)
536                                 synexpect(TRP);
537                         cp->nclist.body = list(0, 0);
538
539                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
540                         if ((t = readtoken()) != TESAC) {
541                                 if (t == TENDCASE)
542                                         ;
543                                 else if (t == TFALLTHRU)
544                                         cp->type = NCLISTFALLTHRU;
545                                 else
546                                         synexpect(TENDCASE);
547                                 checkkwd = CHKNL | CHKKWD, readtoken();
548                         }
549                         cpp = &cp->nclist.next;
550                 }
551                 *cpp = NULL;
552                 checkkwd = CHKKWD | CHKALIAS;
553                 break;
554         case TLP:
555                 n1 = (union node *)stalloc(sizeof (struct nredir));
556                 n1->type = NSUBSHELL;
557                 n1->nredir.n = list(0, 0);
558                 n1->nredir.redirect = NULL;
559                 if (readtoken() != TRP)
560                         synexpect(TRP);
561                 checkkwd = CHKKWD | CHKALIAS;
562                 is_subshell = 1;
563                 break;
564         case TBEGIN:
565                 n1 = list(0, 0);
566                 if (readtoken() != TEND)
567                         synexpect(TEND);
568                 checkkwd = CHKKWD | CHKALIAS;
569                 break;
570         /* Handle an empty command like other simple commands.  */
571         case TBACKGND:
572         case TSEMI:
573         case TAND:
574         case TOR:
575                 /*
576                  * An empty command before a ; doesn't make much sense, and
577                  * should certainly be disallowed in the case of `if ;'.
578                  */
579                 if (!redir)
580                         synexpect(-1);
581         case TNL:
582         case TEOF:
583         case TWORD:
584         case TRP:
585                 tokpushback++;
586                 n1 = simplecmd(rpp, redir);
587                 return n1;
588         default:
589                 synexpect(-1);
590         }
591
592         /* Now check for redirection which may follow command */
593         while (readtoken() == TREDIR) {
594                 *rpp = n2 = redirnode;
595                 rpp = &n2->nfile.next;
596                 parsefname();
597         }
598         tokpushback++;
599         *rpp = NULL;
600         if (redir) {
601                 if (!is_subshell) {
602                         n2 = (union node *)stalloc(sizeof (struct nredir));
603                         n2->type = NREDIR;
604                         n2->nredir.n = n1;
605                         n1 = n2;
606                 }
607                 n1->nredir.redirect = redir;
608         }
609
610         return n1;
611 }
612
613
614 static union node *
615 simplecmd(union node **rpp, union node *redir)
616 {
617         union node *args, **app;
618         union node **orig_rpp = rpp;
619         union node *n = NULL;
620         int special;
621         int savecheckkwd;
622
623         /* If we don't have any redirections already, then we must reset */
624         /* rpp to be the address of the local redir variable.  */
625         if (redir == NULL)
626                 rpp = &redir;
627
628         args = NULL;
629         app = &args;
630         /*
631          * We save the incoming value, because we need this for shell
632          * functions.  There can not be a redirect or an argument between
633          * the function name and the open parenthesis.
634          */
635         orig_rpp = rpp;
636
637         savecheckkwd = CHKALIAS;
638
639         for (;;) {
640                 checkkwd = savecheckkwd;
641                 if (readtoken() == TWORD) {
642                         n = (union node *)stalloc(sizeof (struct narg));
643                         n->type = NARG;
644                         n->narg.text = wordtext;
645                         n->narg.backquote = backquotelist;
646                         *app = n;
647                         app = &n->narg.next;
648                         if (savecheckkwd != 0 && !isassignment(wordtext))
649                                 savecheckkwd = 0;
650                 } else if (lasttoken == TREDIR) {
651                         *rpp = n = redirnode;
652                         rpp = &n->nfile.next;
653                         parsefname();   /* read name of redirection file */
654                 } else if (lasttoken == TLP && app == &args->narg.next
655                                             && rpp == orig_rpp) {
656                         /* We have a function */
657                         if (readtoken() != TRP)
658                                 synexpect(TRP);
659                         funclinno = plinno;
660                         /*
661                          * - Require plain text.
662                          * - Functions with '/' cannot be called.
663                          * - Reject name=().
664                          * - Reject ksh extended glob patterns.
665                          */
666                         if (!noexpand(n->narg.text) || quoteflag ||
667                             strchr(n->narg.text, '/') ||
668                             strchr("!%*+-=?@}~",
669                                 n->narg.text[strlen(n->narg.text) - 1]))
670                                 synerror("Bad function name");
671                         rmescapes(n->narg.text);
672                         if (find_builtin(n->narg.text, &special) >= 0 &&
673                             special)
674                                 synerror("Cannot override a special builtin with a function");
675                         n->type = NDEFUN;
676                         n->narg.next = command();
677                         funclinno = 0;
678                         return n;
679                 } else {
680                         tokpushback++;
681                         break;
682                 }
683         }
684         *app = NULL;
685         *rpp = NULL;
686         n = (union node *)stalloc(sizeof (struct ncmd));
687         n->type = NCMD;
688         n->ncmd.args = args;
689         n->ncmd.redirect = redir;
690         return n;
691 }
692
693 static union node *
694 makename(void)
695 {
696         union node *n;
697
698         n = (union node *)stalloc(sizeof (struct narg));
699         n->type = NARG;
700         n->narg.next = NULL;
701         n->narg.text = wordtext;
702         n->narg.backquote = backquotelist;
703         return n;
704 }
705
706 void
707 fixredir(union node *n, const char *text, int err)
708 {
709         TRACE(("Fix redir %s %d\n", text, err));
710         if (!err)
711                 n->ndup.vname = NULL;
712
713         if (is_digit(text[0]) && text[1] == '\0')
714                 n->ndup.dupfd = digit_val(text[0]);
715         else if (text[0] == '-' && text[1] == '\0')
716                 n->ndup.dupfd = -1;
717         else {
718
719                 if (err)
720                         synerror("Bad fd number");
721                 else
722                         n->ndup.vname = makename();
723         }
724 }
725
726
727 static void
728 parsefname(void)
729 {
730         union node *n = redirnode;
731
732         if (readtoken() != TWORD)
733                 synexpect(-1);
734         if (n->type == NHERE) {
735                 struct heredoc *here = heredoc;
736                 struct heredoc *p;
737                 int i;
738
739                 if (quoteflag == 0)
740                         n->type = NXHERE;
741                 TRACE(("Here document %d\n", n->type));
742                 if (here->striptabs) {
743                         while (*wordtext == '\t')
744                                 wordtext++;
745                 }
746                 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
747                         synerror("Illegal eof marker for << redirection");
748                 rmescapes(wordtext);
749                 here->eofmark = wordtext;
750                 here->next = NULL;
751                 if (heredoclist == NULL)
752                         heredoclist = here;
753                 else {
754                         for (p = heredoclist ; p->next ; p = p->next);
755                         p->next = here;
756                 }
757         } else if (n->type == NTOFD || n->type == NFROMFD) {
758                 fixredir(n, wordtext, 0);
759         } else {
760                 n->nfile.fname = makename();
761         }
762 }
763
764
765 /*
766  * Input any here documents.
767  */
768
769 static void
770 parseheredoc(void)
771 {
772         struct heredoc *here;
773         union node *n;
774
775         while (heredoclist) {
776                 here = heredoclist;
777                 heredoclist = here->next;
778                 if (needprompt) {
779                         setprompt(2);
780                         needprompt = 0;
781                 }
782                 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
783                                 here->eofmark, here->striptabs);
784                 n = (union node *)stalloc(sizeof (struct narg));
785                 n->narg.type = NARG;
786                 n->narg.next = NULL;
787                 n->narg.text = wordtext;
788                 n->narg.backquote = backquotelist;
789                 here->here->nhere.doc = n;
790         }
791 }
792
793 static int
794 peektoken(void)
795 {
796         int t;
797
798         t = readtoken();
799         tokpushback++;
800         return (t);
801 }
802
803 static int
804 readtoken(void)
805 {
806         int t;
807         struct alias *ap;
808 #ifdef DEBUG
809         int alreadyseen = tokpushback;
810 #endif
811
812         top:
813         t = xxreadtoken();
814
815         /*
816          * eat newlines
817          */
818         if (checkkwd & CHKNL) {
819                 while (t == TNL) {
820                         parseheredoc();
821                         t = xxreadtoken();
822                 }
823         }
824
825         /*
826          * check for keywords and aliases
827          */
828         if (t == TWORD && !quoteflag)
829         {
830                 const char * const *pp;
831
832                 if (checkkwd & CHKKWD)
833                         for (pp = parsekwd; *pp; pp++) {
834                                 if (**pp == *wordtext && equal(*pp, wordtext))
835                                 {
836                                         lasttoken = t = pp - parsekwd + KWDOFFSET;
837                                         TRACE(("keyword %s recognized\n", tokname[t]));
838                                         goto out;
839                                 }
840                         }
841                 if (checkkwd & CHKALIAS &&
842                     (ap = lookupalias(wordtext, 1)) != NULL) {
843                         pushstring(ap->val, strlen(ap->val), ap);
844                         goto top;
845                 }
846         }
847 out:
848         if (t != TNOT)
849                 checkkwd = 0;
850
851 #ifdef DEBUG
852         if (!alreadyseen)
853             TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
854         else
855             TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
856 #endif
857         return (t);
858 }
859
860
861 /*
862  * Read the next input token.
863  * If the token is a word, we set backquotelist to the list of cmds in
864  *      backquotes.  We set quoteflag to true if any part of the word was
865  *      quoted.
866  * If the token is TREDIR, then we set redirnode to a structure containing
867  *      the redirection.
868  * In all cases, the variable startlinno is set to the number of the line
869  *      on which the token starts.
870  *
871  * [Change comment:  here documents and internal procedures]
872  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
873  *  word parsing code into a separate routine.  In this case, readtoken
874  *  doesn't need to have any internal procedures, but parseword does.
875  *  We could also make parseoperator in essence the main routine, and
876  *  have parseword (readtoken1?) handle both words and redirection.]
877  */
878
879 #define RETURN(token)   return lasttoken = token
880
881 static int
882 xxreadtoken(void)
883 {
884         int c;
885
886         if (tokpushback) {
887                 tokpushback = 0;
888                 return lasttoken;
889         }
890         if (needprompt) {
891                 setprompt(2);
892                 needprompt = 0;
893         }
894         startlinno = plinno;
895         for (;;) {      /* until token or start of word found */
896                 c = pgetc_macro();
897                 switch (c) {
898                 case ' ': case '\t':
899                         continue;
900                 case '#':
901                         while ((c = pgetc()) != '\n' && c != PEOF);
902                         pungetc();
903                         continue;
904                 case '\\':
905                         if (pgetc() == '\n') {
906                                 startlinno = ++plinno;
907                                 if (doprompt)
908                                         setprompt(2);
909                                 else
910                                         setprompt(0);
911                                 continue;
912                         }
913                         pungetc();
914                         goto breakloop;
915                 case '\n':
916                         plinno++;
917                         needprompt = doprompt;
918                         RETURN(TNL);
919                 case PEOF:
920                         RETURN(TEOF);
921                 case '&':
922                         if (pgetc() == '&')
923                                 RETURN(TAND);
924                         pungetc();
925                         RETURN(TBACKGND);
926                 case '|':
927                         if (pgetc() == '|')
928                                 RETURN(TOR);
929                         pungetc();
930                         RETURN(TPIPE);
931                 case ';':
932                         c = pgetc();
933                         if (c == ';')
934                                 RETURN(TENDCASE);
935                         else if (c == '&')
936                                 RETURN(TFALLTHRU);
937                         pungetc();
938                         RETURN(TSEMI);
939                 case '(':
940                         RETURN(TLP);
941                 case ')':
942                         RETURN(TRP);
943                 default:
944                         goto breakloop;
945                 }
946         }
947 breakloop:
948         return readtoken1(c, BASESYNTAX, NULL, 0);
949 #undef RETURN
950 }
951
952
953 #define MAXNEST_STATIC 8
954 struct tokenstate
955 {
956         const char *syntax; /* *SYNTAX */
957         int parenlevel; /* levels of parentheses in arithmetic */
958         enum tokenstate_category
959         {
960                 TSTATE_TOP,
961                 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
962                 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
963                 TSTATE_ARITH
964         } category;
965 };
966
967
968 /*
969  * Called to parse command substitutions.
970  */
971
972 static char *
973 parsebackq(char *out, struct nodelist **pbqlist,
974     int oldstyle, int dblquote, int quoted)
975 {
976         struct nodelist **nlpp;
977         union node *n;
978         char *volatile str;
979         struct jmploc jmploc;
980         struct jmploc *const savehandler = handler;
981         size_t savelen;
982         int saveprompt;
983         const int bq_startlinno = plinno;
984         char *volatile ostr = NULL;
985         struct parsefile *const savetopfile = getcurrentfile();
986         struct heredoc *const saveheredoclist = heredoclist;
987         struct heredoc *here;
988
989         str = NULL;
990         if (setjmp(jmploc.loc)) {
991                 popfilesupto(savetopfile);
992                 if (str)
993                         ckfree(str);
994                 if (ostr)
995                         ckfree(ostr);
996                 heredoclist = saveheredoclist;
997                 handler = savehandler;
998                 if (exception == EXERROR) {
999                         startlinno = bq_startlinno;
1000                         synerror("Error in command substitution");
1001                 }
1002                 longjmp(handler->loc, 1);
1003         }
1004         INTOFF;
1005         savelen = out - stackblock();
1006         if (savelen > 0) {
1007                 str = ckmalloc(savelen);
1008                 memcpy(str, stackblock(), savelen);
1009         }
1010         handler = &jmploc;
1011         heredoclist = NULL;
1012         INTON;
1013         if (oldstyle) {
1014                 /*
1015                  * We must read until the closing backquote, giving special
1016                  * treatment to some slashes, and then push the string and
1017                  * reread it as input, interpreting it normally.
1018                  */
1019                 char *oout;
1020                 int c, olen;
1021
1022                 STARTSTACKSTR(oout);
1023                 for (;;) {
1024                         if (needprompt) {
1025                                 setprompt(2);
1026                                 needprompt = 0;
1027                         }
1028                         CHECKSTRSPACE(2, oout);
1029                         switch (c = pgetc()) {
1030                         case '`':
1031                                 goto done;
1032
1033                         case '\\':
1034                                 if ((c = pgetc()) == '\n') {
1035                                         plinno++;
1036                                         if (doprompt)
1037                                                 setprompt(2);
1038                                         else
1039                                                 setprompt(0);
1040                                         /*
1041                                          * If eating a newline, avoid putting
1042                                          * the newline into the new character
1043                                          * stream (via the USTPUTC after the
1044                                          * switch).
1045                                          */
1046                                         continue;
1047                                 }
1048                                 if (c != '\\' && c != '`' && c != '$'
1049                                     && (!dblquote || c != '"'))
1050                                         USTPUTC('\\', oout);
1051                                 break;
1052
1053                         case '\n':
1054                                 plinno++;
1055                                 needprompt = doprompt;
1056                                 break;
1057
1058                         case PEOF:
1059                                 startlinno = plinno;
1060                                 synerror("EOF in backquote substitution");
1061                                 break;
1062
1063                         default:
1064                                 break;
1065                         }
1066                         USTPUTC(c, oout);
1067                 }
1068 done:
1069                 USTPUTC('\0', oout);
1070                 olen = oout - stackblock();
1071                 INTOFF;
1072                 ostr = ckmalloc(olen);
1073                 memcpy(ostr, stackblock(), olen);
1074                 setinputstring(ostr, 1);
1075                 INTON;
1076         }
1077         nlpp = pbqlist;
1078         while (*nlpp)
1079                 nlpp = &(*nlpp)->next;
1080         *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1081         (*nlpp)->next = NULL;
1082
1083         if (oldstyle) {
1084                 saveprompt = doprompt;
1085                 doprompt = 0;
1086         }
1087
1088         n = list(0, oldstyle);
1089
1090         if (oldstyle)
1091                 doprompt = saveprompt;
1092         else {
1093                 if (readtoken() != TRP)
1094                         synexpect(TRP);
1095         }
1096
1097         (*nlpp)->n = n;
1098         if (oldstyle) {
1099                 /*
1100                  * Start reading from old file again, ignoring any pushed back
1101                  * tokens left from the backquote parsing
1102                  */
1103                 popfile();
1104                 tokpushback = 0;
1105         }
1106         STARTSTACKSTR(out);
1107         CHECKSTRSPACE(savelen + 1, out);
1108         INTOFF;
1109         if (str) {
1110                 memcpy(out, str, savelen);
1111                 STADJUST(savelen, out);
1112                 ckfree(str);
1113                 str = NULL;
1114         }
1115         if (ostr) {
1116                 ckfree(ostr);
1117                 ostr = NULL;
1118         }
1119         here = saveheredoclist;
1120         if (here != NULL) {
1121                 while (here->next != NULL)
1122                         here = here->next;
1123                 here->next = heredoclist;
1124                 heredoclist = saveheredoclist;
1125         }
1126         handler = savehandler;
1127         INTON;
1128         if (quoted)
1129                 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1130         else
1131                 USTPUTC(CTLBACKQ, out);
1132         return out;
1133 }
1134
1135
1136 /*
1137  * Called to parse a backslash escape sequence inside $'...'.
1138  * The backslash has already been read.
1139  */
1140 static char *
1141 readcstyleesc(char *out)
1142 {
1143         int c, v, i, n;
1144
1145         c = pgetc();
1146         switch (c) {
1147         case '\0':
1148                 synerror("Unterminated quoted string");
1149         case '\n':
1150                 plinno++;
1151                 if (doprompt)
1152                         setprompt(2);
1153                 else
1154                         setprompt(0);
1155                 return out;
1156         case '\\':
1157         case '\'':
1158         case '"':
1159                 v = c;
1160                 break;
1161         case 'a': v = '\a'; break;
1162         case 'b': v = '\b'; break;
1163         case 'e': v = '\033'; break;
1164         case 'f': v = '\f'; break;
1165         case 'n': v = '\n'; break;
1166         case 'r': v = '\r'; break;
1167         case 't': v = '\t'; break;
1168         case 'v': v = '\v'; break;
1169         case 'x':
1170                   v = 0;
1171                   for (;;) {
1172                           c = pgetc();
1173                           if (c >= '0' && c <= '9')
1174                                   v = (v << 4) + c - '0';
1175                           else if (c >= 'A' && c <= 'F')
1176                                   v = (v << 4) + c - 'A' + 10;
1177                           else if (c >= 'a' && c <= 'f')
1178                                   v = (v << 4) + c - 'a' + 10;
1179                           else
1180                                   break;
1181                   }
1182                   pungetc();
1183                   break;
1184         case '0': case '1': case '2': case '3':
1185         case '4': case '5': case '6': case '7':
1186                   v = c - '0';
1187                   c = pgetc();
1188                   if (c >= '0' && c <= '7') {
1189                           v <<= 3;
1190                           v += c - '0';
1191                           c = pgetc();
1192                           if (c >= '0' && c <= '7') {
1193                                   v <<= 3;
1194                                   v += c - '0';
1195                           } else
1196                                   pungetc();
1197                   } else
1198                           pungetc();
1199                   break;
1200         case 'c':
1201                   c = pgetc();
1202                   if (c < 0x3f || c > 0x7a || c == 0x60)
1203                           synerror("Bad escape sequence");
1204                   if (c == '\\' && pgetc() != '\\')
1205                           synerror("Bad escape sequence");
1206                   if (c == '?')
1207                           v = 127;
1208                   else
1209                           v = c & 0x1f;
1210                   break;
1211         case 'u':
1212         case 'U':
1213                   n = c == 'U' ? 8 : 4;
1214                   v = 0;
1215                   for (i = 0; i < n; i++) {
1216                           c = pgetc();
1217                           if (c >= '0' && c <= '9')
1218                                   v = (v << 4) + c - '0';
1219                           else if (c >= 'A' && c <= 'F')
1220                                   v = (v << 4) + c - 'A' + 10;
1221                           else if (c >= 'a' && c <= 'f')
1222                                   v = (v << 4) + c - 'a' + 10;
1223                           else
1224                                   synerror("Bad escape sequence");
1225                   }
1226                   if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1227                           synerror("Bad escape sequence");
1228                   /* We really need iconv here. */
1229                   if (initial_localeisutf8 && v > 127) {
1230                           CHECKSTRSPACE(4, out);
1231                           /*
1232                            * We cannot use wctomb() as the locale may have
1233                            * changed.
1234                            */
1235                           if (v <= 0x7ff) {
1236                                   USTPUTC(0xc0 | v >> 6, out);
1237                                   USTPUTC(0x80 | (v & 0x3f), out);
1238                                   return out;
1239                           } else if (v <= 0xffff) {
1240                                   USTPUTC(0xe0 | v >> 12, out);
1241                                   USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1242                                   USTPUTC(0x80 | (v & 0x3f), out);
1243                                   return out;
1244                           } else if (v <= 0x10ffff) {
1245                                   USTPUTC(0xf0 | v >> 18, out);
1246                                   USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1247                                   USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1248                                   USTPUTC(0x80 | (v & 0x3f), out);
1249                                   return out;
1250                           }
1251                   }
1252                   if (v > 127)
1253                           v = '?';
1254                   break;
1255         default:
1256                   synerror("Bad escape sequence");
1257         }
1258         v = (char)v;
1259         /*
1260          * We can't handle NUL bytes.
1261          * POSIX says we should skip till the closing quote.
1262          */
1263         if (v == '\0') {
1264                 while ((c = pgetc()) != '\'') {
1265                         if (c == '\\')
1266                                 c = pgetc();
1267                         if (c == PEOF)
1268                                 synerror("Unterminated quoted string");
1269                 }
1270                 pungetc();
1271                 return out;
1272         }
1273         if (SQSYNTAX[v] == CCTL)
1274                 USTPUTC(CTLESC, out);
1275         USTPUTC(v, out);
1276         return out;
1277 }
1278
1279
1280 /*
1281  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
1282  * is not NULL, read a here document.  In the latter case, eofmark is the
1283  * word which marks the end of the document and striptabs is true if
1284  * leading tabs should be stripped from the document.  The argument firstc
1285  * is the first character of the input token or document.
1286  *
1287  * Because C does not have internal subroutines, I have simulated them
1288  * using goto's to implement the subroutine linkage.  The following macros
1289  * will run code that appears at the end of readtoken1.
1290  */
1291
1292 #define CHECKEND()      {goto checkend; checkend_return:;}
1293 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
1294 #define PARSESUB()      {goto parsesub; parsesub_return:;}
1295 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
1296
1297 static int
1298 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1299     int striptabs)
1300 {
1301         int c = firstc;
1302         char * volatile out;
1303         int len;
1304         char line[EOFMARKLEN + 1];
1305         struct nodelist *bqlist;
1306         volatile int quotef;
1307         int newvarnest;
1308         int level;
1309         int synentry;
1310         struct tokenstate state_static[MAXNEST_STATIC];
1311         int maxnest = MAXNEST_STATIC;
1312         struct tokenstate *state = state_static;
1313         int sqiscstyle = 0;
1314
1315         startlinno = plinno;
1316         quotef = 0;
1317         bqlist = NULL;
1318         newvarnest = 0;
1319         level = 0;
1320         state[level].syntax = initialsyntax;
1321         state[level].parenlevel = 0;
1322         state[level].category = TSTATE_TOP;
1323
1324         STARTSTACKSTR(out);
1325         loop: { /* for each line, until end of word */
1326                 CHECKEND();     /* set c to PEOF if at end of here document */
1327                 for (;;) {      /* until end of line or end of word */
1328                         CHECKSTRSPACE(4, out);  /* permit 4 calls to USTPUTC */
1329
1330                         synentry = state[level].syntax[c];
1331
1332                         switch(synentry) {
1333                         case CNL:       /* '\n' */
1334                                 if (state[level].syntax == BASESYNTAX)
1335                                         goto endword;   /* exit outer loop */
1336                                 USTPUTC(c, out);
1337                                 plinno++;
1338                                 if (doprompt)
1339                                         setprompt(2);
1340                                 else
1341                                         setprompt(0);
1342                                 c = pgetc();
1343                                 goto loop;              /* continue outer loop */
1344                         case CSBACK:
1345                                 if (sqiscstyle) {
1346                                         out = readcstyleesc(out);
1347                                         break;
1348                                 }
1349                                 /* FALLTHROUGH */
1350                         case CWORD:
1351                                 USTPUTC(c, out);
1352                                 break;
1353                         case CCTL:
1354                                 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1355                                         USTPUTC(CTLESC, out);
1356                                 USTPUTC(c, out);
1357                                 break;
1358                         case CBACK:     /* backslash */
1359                                 c = pgetc();
1360                                 if (c == PEOF) {
1361                                         USTPUTC('\\', out);
1362                                         pungetc();
1363                                 } else if (c == '\n') {
1364                                         plinno++;
1365                                         if (doprompt)
1366                                                 setprompt(2);
1367                                         else
1368                                                 setprompt(0);
1369                                 } else {
1370                                         if (state[level].syntax == DQSYNTAX &&
1371                                             c != '\\' && c != '`' && c != '$' &&
1372                                             (c != '"' || (eofmark != NULL &&
1373                                                 newvarnest == 0)) &&
1374                                             (c != '}' || state[level].category != TSTATE_VAR_OLD))
1375                                                 USTPUTC('\\', out);
1376                                         if ((eofmark == NULL ||
1377                                             newvarnest > 0) &&
1378                                             state[level].syntax == BASESYNTAX)
1379                                                 USTPUTC(CTLQUOTEMARK, out);
1380                                         if (SQSYNTAX[c] == CCTL)
1381                                                 USTPUTC(CTLESC, out);
1382                                         USTPUTC(c, out);
1383                                         if ((eofmark == NULL ||
1384                                             newvarnest > 0) &&
1385                                             state[level].syntax == BASESYNTAX &&
1386                                             state[level].category == TSTATE_VAR_OLD)
1387                                                 USTPUTC(CTLQUOTEEND, out);
1388                                         quotef++;
1389                                 }
1390                                 break;
1391                         case CSQUOTE:
1392                                 USTPUTC(CTLQUOTEMARK, out);
1393                                 state[level].syntax = SQSYNTAX;
1394                                 sqiscstyle = 0;
1395                                 break;
1396                         case CDQUOTE:
1397                                 USTPUTC(CTLQUOTEMARK, out);
1398                                 state[level].syntax = DQSYNTAX;
1399                                 break;
1400                         case CENDQUOTE:
1401                                 if (eofmark != NULL && newvarnest == 0)
1402                                         USTPUTC(c, out);
1403                                 else {
1404                                         if (state[level].category == TSTATE_VAR_OLD)
1405                                                 USTPUTC(CTLQUOTEEND, out);
1406                                         state[level].syntax = BASESYNTAX;
1407                                         quotef++;
1408                                 }
1409                                 break;
1410                         case CVAR:      /* '$' */
1411                                 PARSESUB();             /* parse substitution */
1412                                 break;
1413                         case CENDVAR:   /* '}' */
1414                                 if (level > 0 &&
1415                                     ((state[level].category == TSTATE_VAR_OLD &&
1416                                       state[level].syntax ==
1417                                       state[level - 1].syntax) ||
1418                                     (state[level].category == TSTATE_VAR_NEW &&
1419                                      state[level].syntax == BASESYNTAX))) {
1420                                         if (state[level].category == TSTATE_VAR_NEW)
1421                                                 newvarnest--;
1422                                         level--;
1423                                         USTPUTC(CTLENDVAR, out);
1424                                 } else {
1425                                         USTPUTC(c, out);
1426                                 }
1427                                 break;
1428                         case CLP:       /* '(' in arithmetic */
1429                                 state[level].parenlevel++;
1430                                 USTPUTC(c, out);
1431                                 break;
1432                         case CRP:       /* ')' in arithmetic */
1433                                 if (state[level].parenlevel > 0) {
1434                                         USTPUTC(c, out);
1435                                         --state[level].parenlevel;
1436                                 } else {
1437                                         if (pgetc() == ')') {
1438                                                 if (level > 0 &&
1439                                                     state[level].category == TSTATE_ARITH) {
1440                                                         level--;
1441                                                         USTPUTC(CTLENDARI, out);
1442                                                 } else
1443                                                         USTPUTC(')', out);
1444                                         } else {
1445                                                 /*
1446                                                  * unbalanced parens
1447                                                  *  (don't 2nd guess - no error)
1448                                                  */
1449                                                 pungetc();
1450                                                 USTPUTC(')', out);
1451                                         }
1452                                 }
1453                                 break;
1454                         case CBQUOTE:   /* '`' */
1455                                 out = parsebackq(out, &bqlist, 1,
1456                                     state[level].syntax == DQSYNTAX &&
1457                                     (eofmark == NULL || newvarnest > 0),
1458                                     state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1459                                 break;
1460                         case CEOF:
1461                                 goto endword;           /* exit outer loop */
1462                         case CIGN:
1463                                 break;
1464                         default:
1465                                 if (level == 0)
1466                                         goto endword;   /* exit outer loop */
1467                                 USTPUTC(c, out);
1468                         }
1469                         c = pgetc_macro();
1470                 }
1471         }
1472 endword:
1473         if (state[level].syntax == ARISYNTAX)
1474                 synerror("Missing '))'");
1475         if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1476                 synerror("Unterminated quoted string");
1477         if (state[level].category == TSTATE_VAR_OLD ||
1478             state[level].category == TSTATE_VAR_NEW) {
1479                 startlinno = plinno;
1480                 synerror("Missing '}'");
1481         }
1482         if (state != state_static)
1483                 parser_temp_free_upto(state);
1484         USTPUTC('\0', out);
1485         len = out - stackblock();
1486         out = stackblock();
1487         if (eofmark == NULL) {
1488                 if ((c == '>' || c == '<')
1489                  && quotef == 0
1490                  && len <= 2
1491                  && (*out == '\0' || is_digit(*out))) {
1492                         PARSEREDIR();
1493                         return lasttoken = TREDIR;
1494                 } else {
1495                         pungetc();
1496                 }
1497         }
1498         quoteflag = quotef;
1499         backquotelist = bqlist;
1500         grabstackblock(len);
1501         wordtext = out;
1502         return lasttoken = TWORD;
1503 /* end of readtoken routine */
1504
1505
1506 /*
1507  * Check to see whether we are at the end of the here document.  When this
1508  * is called, c is set to the first character of the next input line.  If
1509  * we are at the end of the here document, this routine sets the c to PEOF.
1510  */
1511
1512 checkend: {
1513         if (eofmark) {
1514                 if (striptabs) {
1515                         while (c == '\t')
1516                                 c = pgetc();
1517                 }
1518                 if (c == *eofmark) {
1519                         if (pfgets(line, sizeof line) != NULL) {
1520                                 const char *p, *q;
1521
1522                                 p = line;
1523                                 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1524                                 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1525                                         c = PEOF;
1526                                         if (*p == '\n') {
1527                                                 plinno++;
1528                                                 needprompt = doprompt;
1529                                         }
1530                                 } else {
1531                                         pushstring(line, strlen(line), NULL);
1532                                 }
1533                         }
1534                 }
1535         }
1536         goto checkend_return;
1537 }
1538
1539
1540 /*
1541  * Parse a redirection operator.  The variable "out" points to a string
1542  * specifying the fd to be redirected.  The variable "c" contains the
1543  * first character of the redirection operator.
1544  */
1545
1546 parseredir: {
1547         char fd = *out;
1548         union node *np;
1549
1550         np = (union node *)stalloc(sizeof (struct nfile));
1551         if (c == '>') {
1552                 np->nfile.fd = 1;
1553                 c = pgetc();
1554                 if (c == '>')
1555                         np->type = NAPPEND;
1556                 else if (c == '&')
1557                         np->type = NTOFD;
1558                 else if (c == '|')
1559                         np->type = NCLOBBER;
1560                 else {
1561                         np->type = NTO;
1562                         pungetc();
1563                 }
1564         } else {        /* c == '<' */
1565                 np->nfile.fd = 0;
1566                 c = pgetc();
1567                 if (c == '<') {
1568                         if (sizeof (struct nfile) != sizeof (struct nhere)) {
1569                                 np = (union node *)stalloc(sizeof (struct nhere));
1570                                 np->nfile.fd = 0;
1571                         }
1572                         np->type = NHERE;
1573                         heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1574                         heredoc->here = np;
1575                         if ((c = pgetc()) == '-') {
1576                                 heredoc->striptabs = 1;
1577                         } else {
1578                                 heredoc->striptabs = 0;
1579                                 pungetc();
1580                         }
1581                 } else if (c == '&')
1582                         np->type = NFROMFD;
1583                 else if (c == '>')
1584                         np->type = NFROMTO;
1585                 else {
1586                         np->type = NFROM;
1587                         pungetc();
1588                 }
1589         }
1590         if (fd != '\0')
1591                 np->nfile.fd = digit_val(fd);
1592         redirnode = np;
1593         goto parseredir_return;
1594 }
1595
1596
1597 /*
1598  * Parse a substitution.  At this point, we have read the dollar sign
1599  * and nothing else.
1600  */
1601
1602 parsesub: {
1603         char buf[10];
1604         int subtype;
1605         int typeloc;
1606         int flags;
1607         char *p;
1608         static const char types[] = "}-+?=";
1609         int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1610         int linno;
1611         int length;
1612         int c1;
1613
1614         c = pgetc();
1615         if (c == '(') { /* $(command) or $((arith)) */
1616                 if (pgetc() == '(') {
1617                         PARSEARITH();
1618                 } else {
1619                         pungetc();
1620                         out = parsebackq(out, &bqlist, 0,
1621                             state[level].syntax == DQSYNTAX &&
1622                             (eofmark == NULL || newvarnest > 0),
1623                             state[level].syntax == DQSYNTAX ||
1624                             state[level].syntax == ARISYNTAX);
1625                 }
1626         } else if (c == '{' || is_name(c) || is_special(c)) {
1627                 USTPUTC(CTLVAR, out);
1628                 typeloc = out - stackblock();
1629                 USTPUTC(VSNORMAL, out);
1630                 subtype = VSNORMAL;
1631                 flags = 0;
1632                 if (c == '{') {
1633                         bracketed_name = 1;
1634                         c = pgetc();
1635                         subtype = 0;
1636                 }
1637 varname:
1638                 if (!is_eof(c) && is_name(c)) {
1639                         length = 0;
1640                         do {
1641                                 STPUTC(c, out);
1642                                 c = pgetc();
1643                                 length++;
1644                         } while (!is_eof(c) && is_in_name(c));
1645                         if (length == 6 &&
1646                             strncmp(out - length, "LINENO", length) == 0) {
1647                                 /* Replace the variable name with the
1648                                  * current line number. */
1649                                 linno = plinno;
1650                                 if (funclinno != 0)
1651                                         linno -= funclinno - 1;
1652                                 snprintf(buf, sizeof(buf), "%d", linno);
1653                                 STADJUST(-6, out);
1654                                 STPUTS(buf, out);
1655                                 flags |= VSLINENO;
1656                         }
1657                 } else if (is_digit(c)) {
1658                         if (bracketed_name) {
1659                                 do {
1660                                         STPUTC(c, out);
1661                                         c = pgetc();
1662                                 } while (is_digit(c));
1663                         } else {
1664                                 STPUTC(c, out);
1665                                 c = pgetc();
1666                         }
1667                 } else if (is_special(c)) {
1668                         c1 = c;
1669                         c = pgetc();
1670                         if (subtype == 0 && c1 == '#') {
1671                                 subtype = VSLENGTH;
1672                                 if (strchr(types, c) == NULL && c != ':' &&
1673                                     c != '#' && c != '%')
1674                                         goto varname;
1675                                 c1 = c;
1676                                 c = pgetc();
1677                                 if (c1 != '}' && c == '}') {
1678                                         pungetc();
1679                                         c = c1;
1680                                         goto varname;
1681                                 }
1682                                 pungetc();
1683                                 c = c1;
1684                                 c1 = '#';
1685                                 subtype = 0;
1686                         }
1687                         USTPUTC(c1, out);
1688                 } else {
1689                         subtype = VSERROR;
1690                         if (c == '}')
1691                                 pungetc();
1692                         else if (c == '\n' || c == PEOF)
1693                                 synerror("Unexpected end of line in substitution");
1694                         else
1695                                 USTPUTC(c, out);
1696                 }
1697                 if (subtype == 0) {
1698                         switch (c) {
1699                         case ':':
1700                                 flags |= VSNUL;
1701                                 c = pgetc();
1702                                 /*FALLTHROUGH*/
1703                         default:
1704                                 p = strchr(types, c);
1705                                 if (p == NULL) {
1706                                         if (c == '\n' || c == PEOF)
1707                                                 synerror("Unexpected end of line in substitution");
1708                                         if (flags == VSNUL)
1709                                                 STPUTC(':', out);
1710                                         STPUTC(c, out);
1711                                         subtype = VSERROR;
1712                                 } else
1713                                         subtype = p - types + VSNORMAL;
1714                                 break;
1715                         case '%':
1716                         case '#':
1717                                 {
1718                                         int cc = c;
1719                                         subtype = c == '#' ? VSTRIMLEFT :
1720                                                              VSTRIMRIGHT;
1721                                         c = pgetc();
1722                                         if (c == cc)
1723                                                 subtype++;
1724                                         else
1725                                                 pungetc();
1726                                         break;
1727                                 }
1728                         }
1729                 } else if (subtype != VSERROR) {
1730                         if (subtype == VSLENGTH && c != '}')
1731                                 subtype = VSERROR;
1732                         pungetc();
1733                 }
1734                 STPUTC('=', out);
1735                 if (state[level].syntax == DQSYNTAX ||
1736                     state[level].syntax == ARISYNTAX)
1737                         flags |= VSQUOTE;
1738                 *(stackblock() + typeloc) = subtype | flags;
1739                 if (subtype != VSNORMAL) {
1740                         if (level + 1 >= maxnest) {
1741                                 maxnest *= 2;
1742                                 if (state == state_static) {
1743                                         state = parser_temp_alloc(
1744                                             maxnest * sizeof(*state));
1745                                         memcpy(state, state_static,
1746                                             MAXNEST_STATIC * sizeof(*state));
1747                                 } else
1748                                         state = parser_temp_realloc(state,
1749                                             maxnest * sizeof(*state));
1750                         }
1751                         level++;
1752                         state[level].parenlevel = 0;
1753                         if (subtype == VSMINUS || subtype == VSPLUS ||
1754                             subtype == VSQUESTION || subtype == VSASSIGN) {
1755                                 /*
1756                                  * For operators that were in the Bourne shell,
1757                                  * inherit the double-quote state.
1758                                  */
1759                                 state[level].syntax = state[level - 1].syntax;
1760                                 state[level].category = TSTATE_VAR_OLD;
1761                         } else {
1762                                 /*
1763                                  * The other operators take a pattern,
1764                                  * so go to BASESYNTAX.
1765                                  * Also, ' and " are now special, even
1766                                  * in here documents.
1767                                  */
1768                                 state[level].syntax = BASESYNTAX;
1769                                 state[level].category = TSTATE_VAR_NEW;
1770                                 newvarnest++;
1771                         }
1772                 }
1773         } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1774                 /* $'cstylequotes' */
1775                 USTPUTC(CTLQUOTEMARK, out);
1776                 state[level].syntax = SQSYNTAX;
1777                 sqiscstyle = 1;
1778         } else {
1779                 USTPUTC('$', out);
1780                 pungetc();
1781         }
1782         goto parsesub_return;
1783 }
1784
1785
1786 /*
1787  * Parse an arithmetic expansion (indicate start of one and set state)
1788  */
1789 parsearith: {
1790
1791         if (level + 1 >= maxnest) {
1792                 maxnest *= 2;
1793                 if (state == state_static) {
1794                         state = parser_temp_alloc(
1795                             maxnest * sizeof(*state));
1796                         memcpy(state, state_static,
1797                             MAXNEST_STATIC * sizeof(*state));
1798                 } else
1799                         state = parser_temp_realloc(state,
1800                             maxnest * sizeof(*state));
1801         }
1802         level++;
1803         state[level].syntax = ARISYNTAX;
1804         state[level].parenlevel = 0;
1805         state[level].category = TSTATE_ARITH;
1806         USTPUTC(CTLARI, out);
1807         if (state[level - 1].syntax == DQSYNTAX)
1808                 USTPUTC('"',out);
1809         else
1810                 USTPUTC(' ',out);
1811         goto parsearith_return;
1812 }
1813
1814 } /* end of readtoken */
1815
1816
1817 void
1818 resetparser(void)
1819 {
1820         tokpushback = 0;
1821         checkkwd = 0;
1822 }
1823
1824
1825 /*
1826  * Returns true if the text contains nothing to expand (no dollar signs
1827  * or backquotes).
1828  */
1829
1830 static int
1831 noexpand(char *text)
1832 {
1833         char *p;
1834         char c;
1835
1836         p = text;
1837         while ((c = *p++) != '\0') {
1838                 if ( c == CTLQUOTEMARK)
1839                         continue;
1840                 if (c == CTLESC)
1841                         p++;
1842                 else if (BASESYNTAX[(int)c] == CCTL)
1843                         return 0;
1844         }
1845         return 1;
1846 }
1847
1848
1849 /*
1850  * Return true if the argument is a legal variable name (a letter or
1851  * underscore followed by zero or more letters, underscores, and digits).
1852  */
1853
1854 int
1855 goodname(const char *name)
1856 {
1857         const char *p;
1858
1859         p = name;
1860         if (! is_name(*p))
1861                 return 0;
1862         while (*++p) {
1863                 if (! is_in_name(*p))
1864                         return 0;
1865         }
1866         return 1;
1867 }
1868
1869
1870 int
1871 isassignment(const char *p)
1872 {
1873         if (!is_name(*p))
1874                 return 0;
1875         p++;
1876         for (;;) {
1877                 if (*p == '=')
1878                         return 1;
1879                 else if (!is_in_name(*p))
1880                         return 0;
1881                 p++;
1882         }
1883 }
1884
1885
1886 /*
1887  * Called when an unexpected token is read during the parse.  The argument
1888  * is the token that is expected, or -1 if more than one type of token can
1889  * occur at this point.
1890  */
1891
1892 static void
1893 synexpect(int token)
1894 {
1895         char msg[64];
1896
1897         if (token >= 0) {
1898                 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1899                         tokname[lasttoken], tokname[token]);
1900         } else {
1901                 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1902         }
1903         synerror(msg);
1904 }
1905
1906
1907 static void
1908 synerror(const char *msg)
1909 {
1910         if (commandname)
1911                 outfmt(out2, "%s: %d: ", commandname, startlinno);
1912         outfmt(out2, "Syntax error: %s\n", msg);
1913         error(NULL);
1914 }
1915
1916 static void
1917 setprompt(int which)
1918 {
1919         whichprompt = which;
1920
1921 #ifndef NO_HISTORY
1922         if (!el)
1923 #endif
1924         {
1925                 out2str(getprompt(NULL));
1926                 flushout(out2);
1927         }
1928 }
1929
1930 /*
1931  * called by editline -- any expansions to the prompt
1932  *    should be added here.
1933  */
1934 const char *
1935 getprompt(void *unused __unused)
1936 {
1937         static char ps[PROMPTLEN];
1938         const char *fmt;
1939         const char *pwd;
1940         int i, trim;
1941
1942         /*
1943          * Select prompt format.
1944          */
1945         switch (whichprompt) {
1946         case 0:
1947                 fmt = "";
1948                 break;
1949         case 1:
1950                 fmt = ps1val();
1951                 break;
1952         case 2:
1953                 fmt = ps2val();
1954                 break;
1955         default:
1956                 return "??";
1957         }
1958
1959         /*
1960          * Format prompt string.
1961          */
1962         for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1963                 if (*fmt == '\\')
1964                         switch (*++fmt) {
1965
1966                                 /*
1967                                  * Hostname.
1968                                  *
1969                                  * \h specifies just the local hostname,
1970                                  * \H specifies fully-qualified hostname.
1971                                  */
1972                         case 'h':
1973                         case 'H':
1974                                 ps[i] = '\0';
1975                                 gethostname(&ps[i], PROMPTLEN - i);
1976                                 /* Skip to end of hostname. */
1977                                 trim = (*fmt == 'h') ? '.' : '\0';
1978                                 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1979                                         i++;
1980                                 break;
1981
1982                                 /*
1983                                  * Working directory.
1984                                  *
1985                                  * \W specifies just the final component,
1986                                  * \w specifies the entire path.
1987                                  */
1988                         case 'W':
1989                         case 'w':
1990                                 pwd = lookupvar("PWD");
1991                                 if (pwd == NULL)
1992                                         pwd = "?";
1993                                 if (*fmt == 'W' &&
1994                                     *pwd == '/' && pwd[1] != '\0')
1995                                         strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1996                                             PROMPTLEN - i);
1997                                 else
1998                                         strlcpy(&ps[i], pwd, PROMPTLEN - i);
1999                                 /* Skip to end of path. */
2000                                 while (ps[i + 1] != '\0')
2001                                         i++;
2002                                 break;
2003
2004                                 /*
2005                                  * Superuser status.
2006                                  *
2007                                  * '$' for normal users, '#' for root.
2008                                  */
2009                         case '$':
2010                                 ps[i] = (geteuid() != 0) ? '$' : '#';
2011                                 break;
2012
2013                                 /*
2014                                  * A literal \.
2015                                  */
2016                         case '\\':
2017                                 ps[i] = '\\';
2018                                 break;
2019
2020                                 /*
2021                                  * Emit unrecognized formats verbatim.
2022                                  */
2023                         default:
2024                                 ps[i++] = '\\';
2025                                 ps[i] = *fmt;
2026                                 break;
2027                         }
2028                 else
2029                         ps[i] = *fmt;
2030         ps[i] = '\0';
2031         return (ps);
2032 }
2033
2034
2035 const char *
2036 expandstr(const char *ps)
2037 {
2038         union node n;
2039         struct jmploc jmploc;
2040         struct jmploc *const savehandler = handler;
2041         const int saveprompt = doprompt;
2042         struct parsefile *const savetopfile = getcurrentfile();
2043         struct parser_temp *const saveparser_temp = parser_temp;
2044         const char *result = NULL;
2045
2046         if (!setjmp(jmploc.loc)) {
2047                 handler = &jmploc;
2048                 parser_temp = NULL;
2049                 setinputstring(ps, 1);
2050                 doprompt = 0;
2051                 readtoken1(pgetc(), DQSYNTAX, __DECONST(char *, "\n\n"), 0);
2052                 if (backquotelist != NULL)
2053                         error("Command substitution not allowed here");
2054
2055                 n.narg.type = NARG;
2056                 n.narg.next = NULL;
2057                 n.narg.text = wordtext;
2058                 n.narg.backquote = backquotelist;
2059
2060                 expandarg(&n, NULL, 0);
2061                 result = stackblock();
2062                 INTOFF;
2063         }
2064         handler = savehandler;
2065         doprompt = saveprompt;
2066         popfilesupto(savetopfile);
2067         if (parser_temp != saveparser_temp) {
2068                 parser_temp_free_all();
2069                 parser_temp = saveparser_temp;
2070         }
2071         if (result != NULL) {
2072                 INTON;
2073         } else if (exception == EXINT)
2074                 raise(SIGINT);
2075         return result;
2076 }