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