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