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