]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - bin/sh/parser.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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
44 #include "shell.h"
45 #include "parser.h"
46 #include "nodes.h"
47 #include "expand.h"     /* defines rmescapes() */
48 #include "syntax.h"
49 #include "options.h"
50 #include "input.h"
51 #include "output.h"
52 #include "var.h"
53 #include "error.h"
54 #include "memalloc.h"
55 #include "mystring.h"
56 #include "alias.h"
57 #include "show.h"
58 #include "eval.h"
59 #ifndef NO_HISTORY
60 #include "myhistedit.h"
61 #endif
62
63 /*
64  * Shell command parser.
65  */
66
67 #define EOFMARKLEN      79
68 #define PROMPTLEN       128
69
70 /* values returned by readtoken */
71 #include "token.h"
72
73
74
75 struct heredoc {
76         struct heredoc *next;   /* next here document in list */
77         union node *here;               /* redirection node */
78         char *eofmark;          /* string indicating end of input */
79         int striptabs;          /* if set, strip leading tabs */
80 };
81
82
83
84 STATIC struct heredoc *heredoclist;     /* list of here documents to read */
85 STATIC int parsebackquote;      /* nonzero if we are inside backquotes */
86 STATIC int doprompt;            /* if set, prompt the user */
87 STATIC int needprompt;          /* true if interactive and at start of line */
88 STATIC int lasttoken;           /* last token read */
89 MKINIT int tokpushback;         /* last token pushed back */
90 STATIC char *wordtext;          /* text of last word returned by readtoken */
91 MKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
92 STATIC struct nodelist *backquotelist;
93 STATIC union node *redirnode;
94 STATIC struct heredoc *heredoc;
95 STATIC int quoteflag;           /* set if (part of) last token was quoted */
96 STATIC int startlinno;          /* line # where last token started */
97 STATIC int funclinno;           /* line # where the current function started */
98
99 /* XXX When 'noaliases' is set to one, no alias expansion takes place. */
100 static int noaliases = 0;
101
102
103 STATIC union node *list(int);
104 STATIC union node *andor(void);
105 STATIC union node *pipeline(void);
106 STATIC union node *command(void);
107 STATIC union node *simplecmd(union node **, union node *);
108 STATIC union node *makename(void);
109 STATIC void parsefname(void);
110 STATIC void parseheredoc(void);
111 STATIC int peektoken(void);
112 STATIC int readtoken(void);
113 STATIC int xxreadtoken(void);
114 STATIC int readtoken1(int, char const *, char *, int);
115 STATIC int noexpand(char *);
116 STATIC void synexpect(int);
117 STATIC void synerror(char *);
118 STATIC void setprompt(int);
119
120
121 /*
122  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
123  * valid parse tree indicating a blank line.)
124  */
125
126 union node *
127 parsecmd(int interact)
128 {
129         int t;
130
131         tokpushback = 0;
132         doprompt = interact;
133         if (doprompt)
134                 setprompt(1);
135         else
136                 setprompt(0);
137         needprompt = 0;
138         t = readtoken();
139         if (t == TEOF)
140                 return NEOF;
141         if (t == TNL)
142                 return NULL;
143         tokpushback++;
144         return list(1);
145 }
146
147
148 STATIC union node *
149 list(int nlflag)
150 {
151         union node *n1, *n2, *n3;
152         int tok;
153
154         checkkwd = 2;
155         if (nlflag == 0 && tokendlist[peektoken()])
156                 return NULL;
157         n1 = NULL;
158         for (;;) {
159                 n2 = andor();
160                 tok = readtoken();
161                 if (tok == TBACKGND) {
162                         if (n2->type == NCMD || n2->type == NPIPE) {
163                                 n2->ncmd.backgnd = 1;
164                         } else if (n2->type == NREDIR) {
165                                 n2->type = NBACKGND;
166                         } else {
167                                 n3 = (union node *)stalloc(sizeof (struct nredir));
168                                 n3->type = NBACKGND;
169                                 n3->nredir.n = n2;
170                                 n3->nredir.redirect = NULL;
171                                 n2 = n3;
172                         }
173                 }
174                 if (n1 == NULL) {
175                         n1 = n2;
176                 }
177                 else {
178                         n3 = (union node *)stalloc(sizeof (struct nbinary));
179                         n3->type = NSEMI;
180                         n3->nbinary.ch1 = n1;
181                         n3->nbinary.ch2 = n2;
182                         n1 = n3;
183                 }
184                 switch (tok) {
185                 case TBACKGND:
186                 case TSEMI:
187                         tok = readtoken();
188                         /* FALLTHROUGH */
189                 case TNL:
190                         if (tok == TNL) {
191                                 parseheredoc();
192                                 if (nlflag)
193                                         return n1;
194                         } else {
195                                 tokpushback++;
196                         }
197                         checkkwd = 2;
198                         if (tokendlist[peektoken()])
199                                 return n1;
200                         break;
201                 case TEOF:
202                         if (heredoclist)
203                                 parseheredoc();
204                         else
205                                 pungetc();              /* push back EOF on input */
206                         return n1;
207                 default:
208                         if (nlflag)
209                                 synexpect(-1);
210                         tokpushback++;
211                         return n1;
212                 }
213         }
214 }
215
216
217
218 STATIC union node *
219 andor(void)
220 {
221         union node *n1, *n2, *n3;
222         int t;
223
224         n1 = pipeline();
225         for (;;) {
226                 if ((t = readtoken()) == TAND) {
227                         t = NAND;
228                 } else if (t == TOR) {
229                         t = NOR;
230                 } else {
231                         tokpushback++;
232                         return n1;
233                 }
234                 n2 = pipeline();
235                 n3 = (union node *)stalloc(sizeof (struct nbinary));
236                 n3->type = t;
237                 n3->nbinary.ch1 = n1;
238                 n3->nbinary.ch2 = n2;
239                 n1 = n3;
240         }
241 }
242
243
244
245 STATIC union node *
246 pipeline(void)
247 {
248         union node *n1, *n2, *pipenode;
249         struct nodelist *lp, *prev;
250         int negate;
251
252         negate = 0;
253         checkkwd = 2;
254         TRACE(("pipeline: entered\n"));
255         while (readtoken() == TNOT)
256                 negate = !negate;
257         tokpushback++;
258         n1 = command();
259         if (readtoken() == TPIPE) {
260                 pipenode = (union node *)stalloc(sizeof (struct npipe));
261                 pipenode->type = NPIPE;
262                 pipenode->npipe.backgnd = 0;
263                 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
264                 pipenode->npipe.cmdlist = lp;
265                 lp->n = n1;
266                 do {
267                         prev = lp;
268                         lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
269                         lp->n = command();
270                         prev->next = lp;
271                 } while (readtoken() == TPIPE);
272                 lp->next = NULL;
273                 n1 = pipenode;
274         }
275         tokpushback++;
276         if (negate) {
277                 n2 = (union node *)stalloc(sizeof (struct nnot));
278                 n2->type = NNOT;
279                 n2->nnot.com = n1;
280                 return n2;
281         } else
282                 return n1;
283 }
284
285
286
287 STATIC union node *
288 command(void)
289 {
290         union node *n1, *n2;
291         union node *ap, **app;
292         union node *cp, **cpp;
293         union node *redir, **rpp;
294         int t, negate = 0;
295
296         checkkwd = 2;
297         redir = NULL;
298         n1 = NULL;
299         rpp = &redir;
300
301         /* Check for redirection which may precede command */
302         while (readtoken() == TREDIR) {
303                 *rpp = n2 = redirnode;
304                 rpp = &n2->nfile.next;
305                 parsefname();
306         }
307         tokpushback++;
308
309         while (readtoken() == TNOT) {
310                 TRACE(("command: TNOT recognized\n"));
311                 negate = !negate;
312         }
313         tokpushback++;
314
315         switch (readtoken()) {
316         case TIF:
317                 n1 = (union node *)stalloc(sizeof (struct nif));
318                 n1->type = NIF;
319                 if ((n1->nif.test = list(0)) == NULL)
320                         synexpect(-1);
321                 if (readtoken() != TTHEN)
322                         synexpect(TTHEN);
323                 n1->nif.ifpart = list(0);
324                 n2 = n1;
325                 while (readtoken() == TELIF) {
326                         n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
327                         n2 = n2->nif.elsepart;
328                         n2->type = NIF;
329                         if ((n2->nif.test = list(0)) == NULL)
330                                 synexpect(-1);
331                         if (readtoken() != TTHEN)
332                                 synexpect(TTHEN);
333                         n2->nif.ifpart = list(0);
334                 }
335                 if (lasttoken == TELSE)
336                         n2->nif.elsepart = list(0);
337                 else {
338                         n2->nif.elsepart = NULL;
339                         tokpushback++;
340                 }
341                 if (readtoken() != TFI)
342                         synexpect(TFI);
343                 checkkwd = 1;
344                 break;
345         case TWHILE:
346         case TUNTIL: {
347                 int got;
348                 n1 = (union node *)stalloc(sizeof (struct nbinary));
349                 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
350                 if ((n1->nbinary.ch1 = list(0)) == NULL)
351                         synexpect(-1);
352                 if ((got=readtoken()) != TDO) {
353 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
354                         synexpect(TDO);
355                 }
356                 n1->nbinary.ch2 = list(0);
357                 if (readtoken() != TDONE)
358                         synexpect(TDONE);
359                 checkkwd = 1;
360                 break;
361         }
362         case TFOR:
363                 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
364                         synerror("Bad for loop variable");
365                 n1 = (union node *)stalloc(sizeof (struct nfor));
366                 n1->type = NFOR;
367                 n1->nfor.var = wordtext;
368                 while (readtoken() == TNL)
369                         ;
370                 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
371                         app = &ap;
372                         while (readtoken() == TWORD) {
373                                 n2 = (union node *)stalloc(sizeof (struct narg));
374                                 n2->type = NARG;
375                                 n2->narg.text = wordtext;
376                                 n2->narg.backquote = backquotelist;
377                                 *app = n2;
378                                 app = &n2->narg.next;
379                         }
380                         *app = NULL;
381                         n1->nfor.args = ap;
382                         if (lasttoken != TNL && lasttoken != TSEMI)
383                                 synexpect(-1);
384                 } else {
385                         static char argvars[5] = {
386                                 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
387                         };
388                         n2 = (union node *)stalloc(sizeof (struct narg));
389                         n2->type = NARG;
390                         n2->narg.text = argvars;
391                         n2->narg.backquote = NULL;
392                         n2->narg.next = NULL;
393                         n1->nfor.args = n2;
394                         /*
395                          * Newline or semicolon here is optional (but note
396                          * that the original Bourne shell only allowed NL).
397                          */
398                         if (lasttoken != TNL && lasttoken != TSEMI)
399                                 tokpushback++;
400                 }
401                 checkkwd = 2;
402                 if ((t = readtoken()) == TDO)
403                         t = TDONE;
404                 else if (t == TBEGIN)
405                         t = TEND;
406                 else
407                         synexpect(-1);
408                 n1->nfor.body = list(0);
409                 if (readtoken() != t)
410                         synexpect(t);
411                 checkkwd = 1;
412                 break;
413         case TCASE:
414                 n1 = (union node *)stalloc(sizeof (struct ncase));
415                 n1->type = NCASE;
416                 if (readtoken() != TWORD)
417                         synexpect(TWORD);
418                 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
419                 n2->type = NARG;
420                 n2->narg.text = wordtext;
421                 n2->narg.backquote = backquotelist;
422                 n2->narg.next = NULL;
423                 while (readtoken() == TNL);
424                 if (lasttoken != TWORD || ! equal(wordtext, "in"))
425                         synerror("expecting \"in\"");
426                 cpp = &n1->ncase.cases;
427                 noaliases = 1;  /* turn off alias expansion */
428                 checkkwd = 2, readtoken();
429                 while (lasttoken != TESAC) {
430                         *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
431                         cp->type = NCLIST;
432                         app = &cp->nclist.pattern;
433                         if (lasttoken == TLP)
434                                 readtoken();
435                         for (;;) {
436                                 *app = ap = (union node *)stalloc(sizeof (struct narg));
437                                 ap->type = NARG;
438                                 ap->narg.text = wordtext;
439                                 ap->narg.backquote = backquotelist;
440                                 if (checkkwd = 2, readtoken() != TPIPE)
441                                         break;
442                                 app = &ap->narg.next;
443                                 readtoken();
444                         }
445                         ap->narg.next = NULL;
446                         if (lasttoken != TRP)
447                                 noaliases = 0, synexpect(TRP);
448                         cp->nclist.body = list(0);
449
450                         checkkwd = 2;
451                         if ((t = readtoken()) != TESAC) {
452                                 if (t != TENDCASE)
453                                         noaliases = 0, synexpect(TENDCASE);
454                                 else
455                                         checkkwd = 2, readtoken();
456                         }
457                         cpp = &cp->nclist.next;
458                 }
459                 noaliases = 0;  /* reset alias expansion */
460                 *cpp = NULL;
461                 checkkwd = 1;
462                 break;
463         case TLP:
464                 n1 = (union node *)stalloc(sizeof (struct nredir));
465                 n1->type = NSUBSHELL;
466                 n1->nredir.n = list(0);
467                 n1->nredir.redirect = NULL;
468                 if (readtoken() != TRP)
469                         synexpect(TRP);
470                 checkkwd = 1;
471                 break;
472         case TBEGIN:
473                 n1 = list(0);
474                 if (readtoken() != TEND)
475                         synexpect(TEND);
476                 checkkwd = 1;
477                 break;
478         /* Handle an empty command like other simple commands.  */
479         case TSEMI:
480         case TAND:
481         case TOR:
482                 /*
483                  * An empty command before a ; doesn't make much sense, and
484                  * should certainly be disallowed in the case of `if ;'.
485                  */
486                 if (!redir)
487                         synexpect(-1);
488         case TNL:
489         case TEOF:
490         case TWORD:
491         case TRP:
492                 tokpushback++;
493                 n1 = simplecmd(rpp, redir);
494                 goto checkneg;
495         default:
496                 synexpect(-1);
497         }
498
499         /* Now check for redirection which may follow command */
500         while (readtoken() == TREDIR) {
501                 *rpp = n2 = redirnode;
502                 rpp = &n2->nfile.next;
503                 parsefname();
504         }
505         tokpushback++;
506         *rpp = NULL;
507         if (redir) {
508                 if (n1->type != NSUBSHELL) {
509                         n2 = (union node *)stalloc(sizeof (struct nredir));
510                         n2->type = NREDIR;
511                         n2->nredir.n = n1;
512                         n1 = n2;
513                 }
514                 n1->nredir.redirect = redir;
515         }
516
517 checkneg:
518         if (negate) {
519                 n2 = (union node *)stalloc(sizeof (struct nnot));
520                 n2->type = NNOT;
521                 n2->nnot.com = n1;
522                 return n2;
523         }
524         else
525                 return n1;
526 }
527
528
529 STATIC union node *
530 simplecmd(union node **rpp, union node *redir)
531 {
532         union node *args, **app;
533         union node **orig_rpp = rpp;
534         union node *n = NULL, *n2;
535         int negate = 0;
536
537         /* If we don't have any redirections already, then we must reset */
538         /* rpp to be the address of the local redir variable.  */
539         if (redir == 0)
540                 rpp = &redir;
541
542         args = NULL;
543         app = &args;
544         /*
545          * We save the incoming value, because we need this for shell
546          * functions.  There can not be a redirect or an argument between
547          * the function name and the open parenthesis.
548          */
549         orig_rpp = rpp;
550
551         while (readtoken() == TNOT) {
552                 TRACE(("command: TNOT recognized\n"));
553                 negate = !negate;
554         }
555         tokpushback++;
556
557         for (;;) {
558                 if (readtoken() == TWORD) {
559                         n = (union node *)stalloc(sizeof (struct narg));
560                         n->type = NARG;
561                         n->narg.text = wordtext;
562                         n->narg.backquote = backquotelist;
563                         *app = n;
564                         app = &n->narg.next;
565                 } else if (lasttoken == TREDIR) {
566                         *rpp = n = redirnode;
567                         rpp = &n->nfile.next;
568                         parsefname();   /* read name of redirection file */
569                 } else if (lasttoken == TLP && app == &args->narg.next
570                                             && rpp == orig_rpp) {
571                         /* We have a function */
572                         if (readtoken() != TRP)
573                                 synexpect(TRP);
574                         funclinno = plinno;
575 #ifdef notdef
576                         if (! goodname(n->narg.text))
577                                 synerror("Bad function name");
578 #endif
579                         n->type = NDEFUN;
580                         n->narg.next = command();
581                         funclinno = 0;
582                         goto checkneg;
583                 } else {
584                         tokpushback++;
585                         break;
586                 }
587         }
588         *app = NULL;
589         *rpp = NULL;
590         n = (union node *)stalloc(sizeof (struct ncmd));
591         n->type = NCMD;
592         n->ncmd.backgnd = 0;
593         n->ncmd.args = args;
594         n->ncmd.redirect = redir;
595
596 checkneg:
597         if (negate) {
598                 n2 = (union node *)stalloc(sizeof (struct nnot));
599                 n2->type = NNOT;
600                 n2->nnot.com = n;
601                 return n2;
602         }
603         else
604                 return n;
605 }
606
607 STATIC union node *
608 makename(void)
609 {
610         union node *n;
611
612         n = (union node *)stalloc(sizeof (struct narg));
613         n->type = NARG;
614         n->narg.next = NULL;
615         n->narg.text = wordtext;
616         n->narg.backquote = backquotelist;
617         return n;
618 }
619
620 void fixredir(union node *n, const char *text, int err)
621 {
622         TRACE(("Fix redir %s %d\n", text, err));
623         if (!err)
624                 n->ndup.vname = NULL;
625
626         if (is_digit(text[0]) && text[1] == '\0')
627                 n->ndup.dupfd = digit_val(text[0]);
628         else if (text[0] == '-' && text[1] == '\0')
629                 n->ndup.dupfd = -1;
630         else {
631
632                 if (err)
633                         synerror("Bad fd number");
634                 else
635                         n->ndup.vname = makename();
636         }
637 }
638
639
640 STATIC void
641 parsefname(void)
642 {
643         union node *n = redirnode;
644
645         if (readtoken() != TWORD)
646                 synexpect(-1);
647         if (n->type == NHERE) {
648                 struct heredoc *here = heredoc;
649                 struct heredoc *p;
650                 int i;
651
652                 if (quoteflag == 0)
653                         n->type = NXHERE;
654                 TRACE(("Here document %d\n", n->type));
655                 if (here->striptabs) {
656                         while (*wordtext == '\t')
657                                 wordtext++;
658                 }
659                 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
660                         synerror("Illegal eof marker for << redirection");
661                 rmescapes(wordtext);
662                 here->eofmark = wordtext;
663                 here->next = NULL;
664                 if (heredoclist == NULL)
665                         heredoclist = here;
666                 else {
667                         for (p = heredoclist ; p->next ; p = p->next);
668                         p->next = here;
669                 }
670         } else if (n->type == NTOFD || n->type == NFROMFD) {
671                 fixredir(n, wordtext, 0);
672         } else {
673                 n->nfile.fname = makename();
674         }
675 }
676
677
678 /*
679  * Input any here documents.
680  */
681
682 STATIC void
683 parseheredoc(void)
684 {
685         struct heredoc *here;
686         union node *n;
687
688         while (heredoclist) {
689                 here = heredoclist;
690                 heredoclist = here->next;
691                 if (needprompt) {
692                         setprompt(2);
693                         needprompt = 0;
694                 }
695                 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
696                                 here->eofmark, here->striptabs);
697                 n = (union node *)stalloc(sizeof (struct narg));
698                 n->narg.type = NARG;
699                 n->narg.next = NULL;
700                 n->narg.text = wordtext;
701                 n->narg.backquote = backquotelist;
702                 here->here->nhere.doc = n;
703         }
704 }
705
706 STATIC int
707 peektoken(void)
708 {
709         int t;
710
711         t = readtoken();
712         tokpushback++;
713         return (t);
714 }
715
716 STATIC int
717 readtoken(void)
718 {
719         int t;
720         int savecheckkwd = checkkwd;
721         struct alias *ap;
722 #ifdef DEBUG
723         int alreadyseen = tokpushback;
724 #endif
725
726         top:
727         t = xxreadtoken();
728
729         if (checkkwd) {
730                 /*
731                  * eat newlines
732                  */
733                 if (checkkwd == 2) {
734                         checkkwd = 0;
735                         while (t == TNL) {
736                                 parseheredoc();
737                                 t = xxreadtoken();
738                         }
739                 } else
740                         checkkwd = 0;
741                 /*
742                  * check for keywords and aliases
743                  */
744                 if (t == TWORD && !quoteflag)
745                 {
746                         const char * const *pp;
747
748                         for (pp = parsekwd; *pp; pp++) {
749                                 if (**pp == *wordtext && equal(*pp, wordtext))
750                                 {
751                                         lasttoken = t = pp - parsekwd + KWDOFFSET;
752                                         TRACE(("keyword %s recognized\n", tokname[t]));
753                                         goto out;
754                                 }
755                         }
756                         if (noaliases == 0 &&
757                             (ap = lookupalias(wordtext, 1)) != NULL) {
758                                 pushstring(ap->val, strlen(ap->val), ap);
759                                 checkkwd = savecheckkwd;
760                                 goto top;
761                         }
762                 }
763 out:
764                 checkkwd = (t == TNOT) ? savecheckkwd : 0;
765         }
766 #ifdef DEBUG
767         if (!alreadyseen)
768             TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
769         else
770             TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
771 #endif
772         return (t);
773 }
774
775
776 /*
777  * Read the next input token.
778  * If the token is a word, we set backquotelist to the list of cmds in
779  *      backquotes.  We set quoteflag to true if any part of the word was
780  *      quoted.
781  * If the token is TREDIR, then we set redirnode to a structure containing
782  *      the redirection.
783  * In all cases, the variable startlinno is set to the number of the line
784  *      on which the token starts.
785  *
786  * [Change comment:  here documents and internal procedures]
787  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
788  *  word parsing code into a separate routine.  In this case, readtoken
789  *  doesn't need to have any internal procedures, but parseword does.
790  *  We could also make parseoperator in essence the main routine, and
791  *  have parseword (readtoken1?) handle both words and redirection.]
792  */
793
794 #define RETURN(token)   return lasttoken = token
795
796 STATIC int
797 xxreadtoken(void)
798 {
799         int c;
800
801         if (tokpushback) {
802                 tokpushback = 0;
803                 return lasttoken;
804         }
805         if (needprompt) {
806                 setprompt(2);
807                 needprompt = 0;
808         }
809         startlinno = plinno;
810         for (;;) {      /* until token or start of word found */
811                 c = pgetc_macro();
812                 if (c == ' ' || c == '\t')
813                         continue;               /* quick check for white space first */
814                 switch (c) {
815                 case ' ': case '\t':
816                         continue;
817                 case '#':
818                         while ((c = pgetc()) != '\n' && c != PEOF);
819                         pungetc();
820                         continue;
821                 case '\\':
822                         if (pgetc() == '\n') {
823                                 startlinno = ++plinno;
824                                 if (doprompt)
825                                         setprompt(2);
826                                 else
827                                         setprompt(0);
828                                 continue;
829                         }
830                         pungetc();
831                         goto breakloop;
832                 case '\n':
833                         plinno++;
834                         needprompt = doprompt;
835                         RETURN(TNL);
836                 case PEOF:
837                         RETURN(TEOF);
838                 case '&':
839                         if (pgetc() == '&')
840                                 RETURN(TAND);
841                         pungetc();
842                         RETURN(TBACKGND);
843                 case '|':
844                         if (pgetc() == '|')
845                                 RETURN(TOR);
846                         pungetc();
847                         RETURN(TPIPE);
848                 case ';':
849                         if (pgetc() == ';')
850                                 RETURN(TENDCASE);
851                         pungetc();
852                         RETURN(TSEMI);
853                 case '(':
854                         RETURN(TLP);
855                 case ')':
856                         RETURN(TRP);
857                 default:
858                         goto breakloop;
859                 }
860         }
861 breakloop:
862         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
863 #undef RETURN
864 }
865
866
867
868 /*
869  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
870  * is not NULL, read a here document.  In the latter case, eofmark is the
871  * word which marks the end of the document and striptabs is true if
872  * leading tabs should be stripped from the document.  The argument firstc
873  * is the first character of the input token or document.
874  *
875  * Because C does not have internal subroutines, I have simulated them
876  * using goto's to implement the subroutine linkage.  The following macros
877  * will run code that appears at the end of readtoken1.
878  */
879
880 #define CHECKEND()      {goto checkend; checkend_return:;}
881 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
882 #define PARSESUB()      {goto parsesub; parsesub_return:;}
883 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
884 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
885 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
886
887 STATIC int
888 readtoken1(int firstc, char const *syntax, char *eofmark, int striptabs)
889 {
890         int c = firstc;
891         char *out;
892         int len;
893         char line[EOFMARKLEN + 1];
894         struct nodelist *bqlist;
895         int quotef;
896         int dblquote;
897         int varnest;    /* levels of variables expansion */
898         int arinest;    /* levels of arithmetic expansion */
899         int parenlevel; /* levels of parens in arithmetic */
900         int oldstyle;
901         char const *prevsyntax; /* syntax before arithmetic */
902         int synentry;
903
904         startlinno = plinno;
905         dblquote = 0;
906         if (syntax == DQSYNTAX)
907                 dblquote = 1;
908         quotef = 0;
909         bqlist = NULL;
910         varnest = 0;
911         arinest = 0;
912         parenlevel = 0;
913
914         STARTSTACKSTR(out);
915         loop: { /* for each line, until end of word */
916                 CHECKEND();     /* set c to PEOF if at end of here document */
917                 for (;;) {      /* until end of line or end of word */
918                         CHECKSTRSPACE(3, out);  /* permit 3 calls to USTPUTC */
919
920                         synentry = syntax[c];
921
922                         switch(synentry) {
923                         case CNL:       /* '\n' */
924                                 if (syntax == BASESYNTAX)
925                                         goto endword;   /* exit outer loop */
926                                 USTPUTC(c, out);
927                                 plinno++;
928                                 if (doprompt)
929                                         setprompt(2);
930                                 else
931                                         setprompt(0);
932                                 c = pgetc();
933                                 goto loop;              /* continue outer loop */
934                         case CWORD:
935                                 USTPUTC(c, out);
936                                 break;
937                         case CCTL:
938                                 if (eofmark == NULL || dblquote)
939                                         USTPUTC(CTLESC, out);
940                                 USTPUTC(c, out);
941                                 break;
942                         case CBACK:     /* backslash */
943                                 c = pgetc();
944                                 if (c == PEOF) {
945                                         USTPUTC('\\', out);
946                                         pungetc();
947                                 } else if (c == '\n') {
948                                         plinno++;
949                                         if (doprompt)
950                                                 setprompt(2);
951                                         else
952                                                 setprompt(0);
953                                 } else {
954                                         if (dblquote && c != '\\' &&
955                                             c != '`' && c != '$' &&
956                                             (c != '"' || eofmark != NULL))
957                                                 USTPUTC('\\', out);
958                                         if (SQSYNTAX[c] == CCTL)
959                                                 USTPUTC(CTLESC, out);
960                                         else if (eofmark == NULL)
961                                                 USTPUTC(CTLQUOTEMARK, out);
962                                         USTPUTC(c, out);
963                                         quotef++;
964                                 }
965                                 break;
966                         case CSQUOTE:
967                                 if (eofmark == NULL)
968                                         USTPUTC(CTLQUOTEMARK, out);
969                                 syntax = SQSYNTAX;
970                                 break;
971                         case CDQUOTE:
972                                 if (eofmark == NULL)
973                                         USTPUTC(CTLQUOTEMARK, out);
974                                 syntax = DQSYNTAX;
975                                 dblquote = 1;
976                                 break;
977                         case CENDQUOTE:
978                                 if (eofmark != NULL && arinest == 0 &&
979                                     varnest == 0) {
980                                         USTPUTC(c, out);
981                                 } else {
982                                         if (arinest) {
983                                                 syntax = ARISYNTAX;
984                                                 dblquote = 0;
985                                         } else if (eofmark == NULL) {
986                                                 syntax = BASESYNTAX;
987                                                 dblquote = 0;
988                                         }
989                                         quotef++;
990                                 }
991                                 break;
992                         case CVAR:      /* '$' */
993                                 PARSESUB();             /* parse substitution */
994                                 break;
995                         case CENDVAR:   /* '}' */
996                                 if (varnest > 0) {
997                                         varnest--;
998                                         USTPUTC(CTLENDVAR, out);
999                                 } else {
1000                                         USTPUTC(c, out);
1001                                 }
1002                                 break;
1003                         case CLP:       /* '(' in arithmetic */
1004                                 parenlevel++;
1005                                 USTPUTC(c, out);
1006                                 break;
1007                         case CRP:       /* ')' in arithmetic */
1008                                 if (parenlevel > 0) {
1009                                         USTPUTC(c, out);
1010                                         --parenlevel;
1011                                 } else {
1012                                         if (pgetc() == ')') {
1013                                                 if (--arinest == 0) {
1014                                                         USTPUTC(CTLENDARI, out);
1015                                                         syntax = prevsyntax;
1016                                                         if (syntax == DQSYNTAX)
1017                                                                 dblquote = 1;
1018                                                         else
1019                                                                 dblquote = 0;
1020                                                 } else
1021                                                         USTPUTC(')', out);
1022                                         } else {
1023                                                 /*
1024                                                  * unbalanced parens
1025                                                  *  (don't 2nd guess - no error)
1026                                                  */
1027                                                 pungetc();
1028                                                 USTPUTC(')', out);
1029                                         }
1030                                 }
1031                                 break;
1032                         case CBQUOTE:   /* '`' */
1033                                 PARSEBACKQOLD();
1034                                 break;
1035                         case CEOF:
1036                                 goto endword;           /* exit outer loop */
1037                         default:
1038                                 if (varnest == 0)
1039                                         goto endword;   /* exit outer loop */
1040                                 USTPUTC(c, out);
1041                         }
1042                         c = pgetc_macro();
1043                 }
1044         }
1045 endword:
1046         if (syntax == ARISYNTAX)
1047                 synerror("Missing '))'");
1048         if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
1049                 synerror("Unterminated quoted string");
1050         if (varnest != 0) {
1051                 startlinno = plinno;
1052                 synerror("Missing '}'");
1053         }
1054         USTPUTC('\0', out);
1055         len = out - stackblock();
1056         out = stackblock();
1057         if (eofmark == NULL) {
1058                 if ((c == '>' || c == '<')
1059                  && quotef == 0
1060                  && len <= 2
1061                  && (*out == '\0' || is_digit(*out))) {
1062                         PARSEREDIR();
1063                         return lasttoken = TREDIR;
1064                 } else {
1065                         pungetc();
1066                 }
1067         }
1068         quoteflag = quotef;
1069         backquotelist = bqlist;
1070         grabstackblock(len);
1071         wordtext = out;
1072         return lasttoken = TWORD;
1073 /* end of readtoken routine */
1074
1075
1076
1077 /*
1078  * Check to see whether we are at the end of the here document.  When this
1079  * is called, c is set to the first character of the next input line.  If
1080  * we are at the end of the here document, this routine sets the c to PEOF.
1081  */
1082
1083 checkend: {
1084         if (eofmark) {
1085                 if (striptabs) {
1086                         while (c == '\t')
1087                                 c = pgetc();
1088                 }
1089                 if (c == *eofmark) {
1090                         if (pfgets(line, sizeof line) != NULL) {
1091                                 char *p, *q;
1092
1093                                 p = line;
1094                                 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1095                                 if (*p == '\n' && *q == '\0') {
1096                                         c = PEOF;
1097                                         plinno++;
1098                                         needprompt = doprompt;
1099                                 } else {
1100                                         pushstring(line, strlen(line), NULL);
1101                                 }
1102                         }
1103                 }
1104         }
1105         goto checkend_return;
1106 }
1107
1108
1109 /*
1110  * Parse a redirection operator.  The variable "out" points to a string
1111  * specifying the fd to be redirected.  The variable "c" contains the
1112  * first character of the redirection operator.
1113  */
1114
1115 parseredir: {
1116         char fd = *out;
1117         union node *np;
1118
1119         np = (union node *)stalloc(sizeof (struct nfile));
1120         if (c == '>') {
1121                 np->nfile.fd = 1;
1122                 c = pgetc();
1123                 if (c == '>')
1124                         np->type = NAPPEND;
1125                 else if (c == '&')
1126                         np->type = NTOFD;
1127                 else if (c == '|')
1128                         np->type = NCLOBBER;
1129                 else {
1130                         np->type = NTO;
1131                         pungetc();
1132                 }
1133         } else {        /* c == '<' */
1134                 np->nfile.fd = 0;
1135                 c = pgetc();
1136                 if (c == '<') {
1137                         if (sizeof (struct nfile) != sizeof (struct nhere)) {
1138                                 np = (union node *)stalloc(sizeof (struct nhere));
1139                                 np->nfile.fd = 0;
1140                         }
1141                         np->type = NHERE;
1142                         heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1143                         heredoc->here = np;
1144                         if ((c = pgetc()) == '-') {
1145                                 heredoc->striptabs = 1;
1146                         } else {
1147                                 heredoc->striptabs = 0;
1148                                 pungetc();
1149                         }
1150                 } else if (c == '&')
1151                         np->type = NFROMFD;
1152                 else if (c == '>')
1153                         np->type = NFROMTO;
1154                 else {
1155                         np->type = NFROM;
1156                         pungetc();
1157                 }
1158         }
1159         if (fd != '\0')
1160                 np->nfile.fd = digit_val(fd);
1161         redirnode = np;
1162         goto parseredir_return;
1163 }
1164
1165
1166 /*
1167  * Parse a substitution.  At this point, we have read the dollar sign
1168  * and nothing else.
1169  */
1170
1171 parsesub: {
1172         char buf[10];
1173         int subtype;
1174         int typeloc;
1175         int flags;
1176         char *p;
1177         static const char types[] = "}-+?=";
1178         int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1179         int i;
1180         int linno;
1181         int length;
1182
1183         c = pgetc();
1184         if (c != '(' && c != '{' && (is_eof(c) || !is_name(c)) &&
1185             !is_special(c)) {
1186                 USTPUTC('$', out);
1187                 pungetc();
1188         } else if (c == '(') {  /* $(command) or $((arith)) */
1189                 if (pgetc() == '(') {
1190                         PARSEARITH();
1191                 } else {
1192                         pungetc();
1193                         PARSEBACKQNEW();
1194                 }
1195         } else {
1196                 USTPUTC(CTLVAR, out);
1197                 typeloc = out - stackblock();
1198                 USTPUTC(VSNORMAL, out);
1199                 subtype = VSNORMAL;
1200                 flags = 0;
1201                 if (c == '{') {
1202                         bracketed_name = 1;
1203                         c = pgetc();
1204                         if (c == '#') {
1205                                 if ((c = pgetc()) == '}')
1206                                         c = '#';
1207                                 else
1208                                         subtype = VSLENGTH;
1209                         }
1210                         else
1211                                 subtype = 0;
1212                 }
1213                 if (!is_eof(c) && is_name(c)) {
1214                         length = 0;
1215                         do {
1216                                 STPUTC(c, out);
1217                                 c = pgetc();
1218                                 length++;
1219                         } while (!is_eof(c) && is_in_name(c));
1220                         if (length == 6 &&
1221                             strncmp(out - length, "LINENO", length) == 0) {
1222                                 /* Replace the variable name with the
1223                                  * current line number. */
1224                                 linno = plinno;
1225                                 if (funclinno != 0)
1226                                         linno -= funclinno - 1;
1227                                 snprintf(buf, sizeof(buf), "%d", linno);
1228                                 STADJUST(-6, out);
1229                                 for (i = 0; buf[i] != '\0'; i++)
1230                                         STPUTC(buf[i], out);
1231                                 flags |= VSLINENO;
1232                         }
1233                 } else if (is_digit(c)) {
1234                         if (bracketed_name) {
1235                                 do {
1236                                         STPUTC(c, out);
1237                                         c = pgetc();
1238                                 } while (is_digit(c));
1239                         } else {
1240                                 STPUTC(c, out);
1241                                 c = pgetc();
1242                         }
1243                 } else {
1244                         if (! is_special(c)) {
1245                                 subtype = VSERROR;
1246                                 if (c == '}')
1247                                         pungetc();
1248                                 else
1249                                         USTPUTC(c, out);
1250                         } else {
1251                                 USTPUTC(c, out);
1252                                 c = pgetc();
1253                         }
1254                 }
1255                 if (subtype == 0) {
1256                         switch (c) {
1257                         case ':':
1258                                 flags |= VSNUL;
1259                                 c = pgetc();
1260                                 /*FALLTHROUGH*/
1261                         default:
1262                                 p = strchr(types, c);
1263                                 if (p == NULL) {
1264                                         if (flags == VSNUL)
1265                                                 STPUTC(':', out);
1266                                         STPUTC(c, out);
1267                                         subtype = VSERROR;
1268                                 } else
1269                                         subtype = p - types + VSNORMAL;
1270                                 break;
1271                         case '%':
1272                         case '#':
1273                                 {
1274                                         int cc = c;
1275                                         subtype = c == '#' ? VSTRIMLEFT :
1276                                                              VSTRIMRIGHT;
1277                                         c = pgetc();
1278                                         if (c == cc)
1279                                                 subtype++;
1280                                         else
1281                                                 pungetc();
1282                                         break;
1283                                 }
1284                         }
1285                 } else if (subtype != VSERROR) {
1286                         pungetc();
1287                 }
1288                 STPUTC('=', out);
1289                 if (subtype != VSLENGTH && (dblquote || arinest))
1290                         flags |= VSQUOTE;
1291                 *(stackblock() + typeloc) = subtype | flags;
1292                 if (subtype != VSNORMAL)
1293                         varnest++;
1294         }
1295         goto parsesub_return;
1296 }
1297
1298
1299 /*
1300  * Called to parse command substitutions.  Newstyle is set if the command
1301  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
1302  * list of commands (passed by reference), and savelen is the number of
1303  * characters on the top of the stack which must be preserved.
1304  */
1305
1306 parsebackq: {
1307         struct nodelist **nlpp;
1308         int savepbq;
1309         union node *n;
1310         char *volatile str;
1311         struct jmploc jmploc;
1312         struct jmploc *const savehandler = handler;
1313         int savelen;
1314         int saveprompt;
1315         const int bq_startlinno = plinno;
1316
1317         savepbq = parsebackquote;
1318         if (setjmp(jmploc.loc)) {
1319                 if (str)
1320                         ckfree(str);
1321                 parsebackquote = 0;
1322                 handler = savehandler;
1323                 if (exception == EXERROR) {
1324                         startlinno = bq_startlinno;
1325                         synerror("Error in command substitution");
1326                 }
1327                 longjmp(handler->loc, 1);
1328         }
1329         INTOFF;
1330         str = NULL;
1331         savelen = out - stackblock();
1332         if (savelen > 0) {
1333                 str = ckmalloc(savelen);
1334                 memcpy(str, stackblock(), savelen);
1335         }
1336         handler = &jmploc;
1337         INTON;
1338         if (oldstyle) {
1339                 /* We must read until the closing backquote, giving special
1340                    treatment to some slashes, and then push the string and
1341                    reread it as input, interpreting it normally.  */
1342                 char *out;
1343                 int c;
1344                 int savelen;
1345                 char *str;
1346
1347
1348                 STARTSTACKSTR(out);
1349                 for (;;) {
1350                         if (needprompt) {
1351                                 setprompt(2);
1352                                 needprompt = 0;
1353                         }
1354                         switch (c = pgetc()) {
1355                         case '`':
1356                                 goto done;
1357
1358                         case '\\':
1359                                 if ((c = pgetc()) == '\n') {
1360                                         plinno++;
1361                                         if (doprompt)
1362                                                 setprompt(2);
1363                                         else
1364                                                 setprompt(0);
1365                                         /*
1366                                          * If eating a newline, avoid putting
1367                                          * the newline into the new character
1368                                          * stream (via the STPUTC after the
1369                                          * switch).
1370                                          */
1371                                         continue;
1372                                 }
1373                                 if (c != '\\' && c != '`' && c != '$'
1374                                     && (!dblquote || c != '"'))
1375                                         STPUTC('\\', out);
1376                                 break;
1377
1378                         case '\n':
1379                                 plinno++;
1380                                 needprompt = doprompt;
1381                                 break;
1382
1383                         case PEOF:
1384                                 startlinno = plinno;
1385                                 synerror("EOF in backquote substitution");
1386                                 break;
1387
1388                         default:
1389                                 break;
1390                         }
1391                         STPUTC(c, out);
1392                 }
1393 done:
1394                 STPUTC('\0', out);
1395                 savelen = out - stackblock();
1396                 if (savelen > 0) {
1397                         str = ckmalloc(savelen);
1398                         memcpy(str, stackblock(), savelen);
1399                         setinputstring(str, 1);
1400                 }
1401         }
1402         nlpp = &bqlist;
1403         while (*nlpp)
1404                 nlpp = &(*nlpp)->next;
1405         *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1406         (*nlpp)->next = NULL;
1407         parsebackquote = oldstyle;
1408
1409         if (oldstyle) {
1410                 saveprompt = doprompt;
1411                 doprompt = 0;
1412         }
1413
1414         n = list(0);
1415
1416         if (oldstyle)
1417                 doprompt = saveprompt;
1418         else {
1419                 if (readtoken() != TRP)
1420                         synexpect(TRP);
1421         }
1422
1423         (*nlpp)->n = n;
1424         if (oldstyle) {
1425                 /*
1426                  * Start reading from old file again, ignoring any pushed back
1427                  * tokens left from the backquote parsing
1428                  */
1429                 popfile();
1430                 tokpushback = 0;
1431         }
1432         while (stackblocksize() <= savelen)
1433                 growstackblock();
1434         STARTSTACKSTR(out);
1435         if (str) {
1436                 memcpy(out, str, savelen);
1437                 STADJUST(savelen, out);
1438                 INTOFF;
1439                 ckfree(str);
1440                 str = NULL;
1441                 INTON;
1442         }
1443         parsebackquote = savepbq;
1444         handler = savehandler;
1445         if (arinest || dblquote)
1446                 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1447         else
1448                 USTPUTC(CTLBACKQ, out);
1449         if (oldstyle)
1450                 goto parsebackq_oldreturn;
1451         else
1452                 goto parsebackq_newreturn;
1453 }
1454
1455 /*
1456  * Parse an arithmetic expansion (indicate start of one and set state)
1457  */
1458 parsearith: {
1459
1460         if (++arinest == 1) {
1461                 prevsyntax = syntax;
1462                 syntax = ARISYNTAX;
1463                 USTPUTC(CTLARI, out);
1464                 if (dblquote)
1465                         USTPUTC('"',out);
1466                 else
1467                         USTPUTC(' ',out);
1468         } else {
1469                 /*
1470                  * we collapse embedded arithmetic expansion to
1471                  * parenthesis, which should be equivalent
1472                  */
1473                 USTPUTC('(', out);
1474         }
1475         goto parsearith_return;
1476 }
1477
1478 } /* end of readtoken */
1479
1480
1481
1482 #ifdef mkinit
1483 RESET {
1484         tokpushback = 0;
1485         checkkwd = 0;
1486 }
1487 #endif
1488
1489 /*
1490  * Returns true if the text contains nothing to expand (no dollar signs
1491  * or backquotes).
1492  */
1493
1494 STATIC int
1495 noexpand(char *text)
1496 {
1497         char *p;
1498         char c;
1499
1500         p = text;
1501         while ((c = *p++) != '\0') {
1502                 if ( c == CTLQUOTEMARK)
1503                         continue;
1504                 if (c == CTLESC)
1505                         p++;
1506                 else if (BASESYNTAX[(int)c] == CCTL)
1507                         return 0;
1508         }
1509         return 1;
1510 }
1511
1512
1513 /*
1514  * Return true if the argument is a legal variable name (a letter or
1515  * underscore followed by zero or more letters, underscores, and digits).
1516  */
1517
1518 int
1519 goodname(char *name)
1520 {
1521         char *p;
1522
1523         p = name;
1524         if (! is_name(*p))
1525                 return 0;
1526         while (*++p) {
1527                 if (! is_in_name(*p))
1528                         return 0;
1529         }
1530         return 1;
1531 }
1532
1533
1534 /*
1535  * Called when an unexpected token is read during the parse.  The argument
1536  * is the token that is expected, or -1 if more than one type of token can
1537  * occur at this point.
1538  */
1539
1540 STATIC void
1541 synexpect(int token)
1542 {
1543         char msg[64];
1544
1545         if (token >= 0) {
1546                 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1547                         tokname[lasttoken], tokname[token]);
1548         } else {
1549                 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1550         }
1551         synerror(msg);
1552 }
1553
1554
1555 STATIC void
1556 synerror(char *msg)
1557 {
1558         if (commandname)
1559                 outfmt(&errout, "%s: %d: ", commandname, startlinno);
1560         outfmt(&errout, "Syntax error: %s\n", msg);
1561         error((char *)NULL);
1562 }
1563
1564 STATIC void
1565 setprompt(int which)
1566 {
1567         whichprompt = which;
1568
1569 #ifndef NO_HISTORY
1570         if (!el)
1571 #endif
1572                 out2str(getprompt(NULL));
1573 }
1574
1575 /*
1576  * called by editline -- any expansions to the prompt
1577  *    should be added here.
1578  */
1579 char *
1580 getprompt(void *unused __unused)
1581 {
1582         static char ps[PROMPTLEN];
1583         char *fmt;
1584         int i, j, trim;
1585
1586         /*
1587          * Select prompt format.
1588          */
1589         switch (whichprompt) {
1590         case 0:
1591                 fmt = "";
1592                 break;
1593         case 1:
1594                 fmt = ps1val();
1595                 break;
1596         case 2:
1597                 fmt = ps2val();
1598                 break;
1599         default:
1600                 return "<internal prompt error>";
1601         }
1602
1603         /*
1604          * Format prompt string.
1605          */
1606         for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1607                 if (*fmt == '\\')
1608                         switch (*++fmt) {
1609
1610                                 /*
1611                                  * Hostname.
1612                                  *
1613                                  * \h specifies just the local hostname,
1614                                  * \H specifies fully-qualified hostname.
1615                                  */
1616                         case 'h':
1617                         case 'H':
1618                                 ps[i] = '\0';
1619                                 gethostname(&ps[i], PROMPTLEN - i);
1620                                 /* Skip to end of hostname. */
1621                                 trim = (*fmt == 'h') ? '.' : '\0';
1622                                 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1623                                         i++;
1624                                 break;
1625
1626                                 /*
1627                                  * Working directory.
1628                                  *
1629                                  * \W specifies just the final component,
1630                                  * \w specifies the entire path.
1631                                  */
1632                         case 'W':
1633                         case 'w':
1634                                 ps[i] = '\0';
1635                                 getcwd(&ps[i], PROMPTLEN - i);
1636                                 if (*fmt == 'W' && ps[i + 1] != '\0') {
1637                                         /* Final path component only. */
1638                                         trim = 1;
1639                                         for (j = i; ps[j] != '\0'; j++)
1640                                           if (ps[j] == '/')
1641                                                 trim = j + 1;
1642                                         memmove(&ps[i], &ps[trim],
1643                                             j - trim + 1);
1644                                 }
1645                                 /* Skip to end of path. */
1646                                 while (ps[i + 1] != '\0')
1647                                         i++;
1648                                 break;
1649
1650                                 /*
1651                                  * Superuser status.
1652                                  *
1653                                  * '$' for normal users, '#' for root.
1654                                  */
1655                         case '$':
1656                                 ps[i] = (geteuid() != 0) ? '$' : '#';
1657                                 break;
1658
1659                                 /*
1660                                  * A literal \.
1661                                  */
1662                         case '\\':
1663                                 ps[i] = '\\';
1664                                 break;
1665
1666                                 /*
1667                                  * Emit unrecognized formats verbatim.
1668                                  */
1669                         default:
1670                                 ps[i++] = '\\';
1671                                 ps[i] = *fmt;
1672                                 break;
1673                         }
1674                 else
1675                         ps[i] = *fmt;
1676         ps[i] = '\0';
1677         return (ps);
1678 }