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