parser.c revision 206144
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/parser.c 206144 2010-04-03 20:35:39Z jilles $");
401556Srgrimes
4117987Speter#include <stdlib.h>
42149017Sstefanf#include <unistd.h>
4317987Speter
441556Srgrimes#include "shell.h"
451556Srgrimes#include "parser.h"
461556Srgrimes#include "nodes.h"
471556Srgrimes#include "expand.h"	/* defines rmescapes() */
481556Srgrimes#include "syntax.h"
491556Srgrimes#include "options.h"
501556Srgrimes#include "input.h"
511556Srgrimes#include "output.h"
521556Srgrimes#include "var.h"
531556Srgrimes#include "error.h"
541556Srgrimes#include "memalloc.h"
551556Srgrimes#include "mystring.h"
561556Srgrimes#include "alias.h"
5717987Speter#include "show.h"
5859436Scracauer#include "eval.h"
5917987Speter#ifndef NO_HISTORY
601556Srgrimes#include "myhistedit.h"
6117987Speter#endif
621556Srgrimes
631556Srgrimes/*
641556Srgrimes * Shell command parser.
651556Srgrimes */
661556Srgrimes
67142845Sobrien#define	EOFMARKLEN	79
68142845Sobrien#define	PROMPTLEN	128
691556Srgrimes
701556Srgrimes/* values returned by readtoken */
7117987Speter#include "token.h"
721556Srgrimes
731556Srgrimes
741556Srgrimes
751556Srgrimesstruct heredoc {
761556Srgrimes	struct heredoc *next;	/* next here document in list */
771556Srgrimes	union node *here;		/* redirection node */
781556Srgrimes	char *eofmark;		/* string indicating end of input */
791556Srgrimes	int striptabs;		/* if set, strip leading tabs */
801556Srgrimes};
811556Srgrimes
821556Srgrimes
831556Srgrimes
84117261SddsSTATIC struct heredoc *heredoclist;	/* list of here documents to read */
85117261SddsSTATIC int doprompt;		/* if set, prompt the user */
86117261SddsSTATIC int needprompt;		/* true if interactive and at start of line */
87117261SddsSTATIC int lasttoken;		/* last token read */
881556SrgrimesMKINIT int tokpushback;		/* last token pushed back */
89117261SddsSTATIC char *wordtext;		/* text of last word returned by readtoken */
901556SrgrimesMKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
91117261SddsSTATIC struct nodelist *backquotelist;
92117261SddsSTATIC union node *redirnode;
93117261SddsSTATIC struct heredoc *heredoc;
94117261SddsSTATIC int quoteflag;		/* set if (part of) last token was quoted */
95117261SddsSTATIC int startlinno;		/* line # where last token started */
96179022SstefanfSTATIC int funclinno;		/* line # where the current function started */
971556Srgrimes
9818018Speter/* XXX When 'noaliases' is set to one, no alias expansion takes place. */
9918018Speterstatic int noaliases = 0;
1001556Srgrimes
1011556Srgrimes
10290111SimpSTATIC union node *list(int);
10390111SimpSTATIC union node *andor(void);
10490111SimpSTATIC union node *pipeline(void);
10590111SimpSTATIC union node *command(void);
10690111SimpSTATIC union node *simplecmd(union node **, union node *);
10790111SimpSTATIC union node *makename(void);
10890111SimpSTATIC void parsefname(void);
10990111SimpSTATIC void parseheredoc(void);
11090111SimpSTATIC int peektoken(void);
11190111SimpSTATIC int readtoken(void);
11290111SimpSTATIC int xxreadtoken(void);
11390111SimpSTATIC int readtoken1(int, char const *, char *, int);
11490111SimpSTATIC int noexpand(char *);
11590111SimpSTATIC void synexpect(int);
116201053SjillesSTATIC void synerror(const char *);
11790111SimpSTATIC void setprompt(int);
1181556Srgrimes
11917987Speter
1201556Srgrimes/*
1211556Srgrimes * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
1221556Srgrimes * valid parse tree indicating a blank line.)
1231556Srgrimes */
1241556Srgrimes
1251556Srgrimesunion node *
12690111Simpparsecmd(int interact)
12717987Speter{
1281556Srgrimes	int t;
1291556Srgrimes
13060593Scracauer	tokpushback = 0;
1311556Srgrimes	doprompt = interact;
1321556Srgrimes	if (doprompt)
1331556Srgrimes		setprompt(1);
1341556Srgrimes	else
1351556Srgrimes		setprompt(0);
1361556Srgrimes	needprompt = 0;
1371556Srgrimes	t = readtoken();
1381556Srgrimes	if (t == TEOF)
1391556Srgrimes		return NEOF;
1401556Srgrimes	if (t == TNL)
1411556Srgrimes		return NULL;
1421556Srgrimes	tokpushback++;
1431556Srgrimes	return list(1);
1441556Srgrimes}
1451556Srgrimes
1461556Srgrimes
1471556SrgrimesSTATIC union node *
14890111Simplist(int nlflag)
14917987Speter{
1501556Srgrimes	union node *n1, *n2, *n3;
15117987Speter	int tok;
1521556Srgrimes
1531556Srgrimes	checkkwd = 2;
1541556Srgrimes	if (nlflag == 0 && tokendlist[peektoken()])
1551556Srgrimes		return NULL;
15617987Speter	n1 = NULL;
1571556Srgrimes	for (;;) {
15817987Speter		n2 = andor();
15917987Speter		tok = readtoken();
16017987Speter		if (tok == TBACKGND) {
16117987Speter			if (n2->type == NCMD || n2->type == NPIPE) {
16217987Speter				n2->ncmd.backgnd = 1;
16317987Speter			} else if (n2->type == NREDIR) {
16417987Speter				n2->type = NBACKGND;
16517987Speter			} else {
16617987Speter				n3 = (union node *)stalloc(sizeof (struct nredir));
16717987Speter				n3->type = NBACKGND;
16817987Speter				n3->nredir.n = n2;
16917987Speter				n3->nredir.redirect = NULL;
17017987Speter				n2 = n3;
17117987Speter			}
17217987Speter		}
17317987Speter		if (n1 == NULL) {
17417987Speter			n1 = n2;
17517987Speter		}
17617987Speter		else {
17717987Speter			n3 = (union node *)stalloc(sizeof (struct nbinary));
17817987Speter			n3->type = NSEMI;
17917987Speter			n3->nbinary.ch1 = n1;
18017987Speter			n3->nbinary.ch2 = n2;
18117987Speter			n1 = n3;
18217987Speter		}
18317987Speter		switch (tok) {
18413882Sjoerg		case TBACKGND:
18517987Speter		case TSEMI:
18617987Speter			tok = readtoken();
187102410Scharnier			/* FALLTHROUGH */
1881556Srgrimes		case TNL:
18917987Speter			if (tok == TNL) {
19017987Speter				parseheredoc();
19117987Speter				if (nlflag)
19217987Speter					return n1;
19317987Speter			} else {
19417987Speter				tokpushback++;
19517987Speter			}
1961556Srgrimes			checkkwd = 2;
1971556Srgrimes			if (tokendlist[peektoken()])
1981556Srgrimes				return n1;
1991556Srgrimes			break;
2001556Srgrimes		case TEOF:
2011556Srgrimes			if (heredoclist)
2021556Srgrimes				parseheredoc();
2031556Srgrimes			else
2041556Srgrimes				pungetc();		/* push back EOF on input */
2051556Srgrimes			return n1;
2061556Srgrimes		default:
2071556Srgrimes			if (nlflag)
2081556Srgrimes				synexpect(-1);
2091556Srgrimes			tokpushback++;
2101556Srgrimes			return n1;
2111556Srgrimes		}
2121556Srgrimes	}
2131556Srgrimes}
2141556Srgrimes
2151556Srgrimes
2161556Srgrimes
2171556SrgrimesSTATIC union node *
21890111Simpandor(void)
21990111Simp{
2201556Srgrimes	union node *n1, *n2, *n3;
2211556Srgrimes	int t;
2221556Srgrimes
2231556Srgrimes	n1 = pipeline();
2241556Srgrimes	for (;;) {
2251556Srgrimes		if ((t = readtoken()) == TAND) {
2261556Srgrimes			t = NAND;
2271556Srgrimes		} else if (t == TOR) {
2281556Srgrimes			t = NOR;
2291556Srgrimes		} else {
2301556Srgrimes			tokpushback++;
2311556Srgrimes			return n1;
2321556Srgrimes		}
2331556Srgrimes		n2 = pipeline();
2341556Srgrimes		n3 = (union node *)stalloc(sizeof (struct nbinary));
2351556Srgrimes		n3->type = t;
2361556Srgrimes		n3->nbinary.ch1 = n1;
2371556Srgrimes		n3->nbinary.ch2 = n2;
2381556Srgrimes		n1 = n3;
2391556Srgrimes	}
2401556Srgrimes}
2411556Srgrimes
2421556Srgrimes
2431556Srgrimes
2441556SrgrimesSTATIC union node *
24590111Simppipeline(void)
24690111Simp{
24775336Sbrian	union node *n1, *n2, *pipenode;
2481556Srgrimes	struct nodelist *lp, *prev;
24975336Sbrian	int negate;
2501556Srgrimes
25175336Sbrian	negate = 0;
252191009Sstefanf	checkkwd = 2;
2531556Srgrimes	TRACE(("pipeline: entered\n"));
25475336Sbrian	while (readtoken() == TNOT)
25575336Sbrian		negate = !negate;
25675336Sbrian	tokpushback++;
2571556Srgrimes	n1 = command();
2581556Srgrimes	if (readtoken() == TPIPE) {
2591556Srgrimes		pipenode = (union node *)stalloc(sizeof (struct npipe));
2601556Srgrimes		pipenode->type = NPIPE;
2611556Srgrimes		pipenode->npipe.backgnd = 0;
2621556Srgrimes		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
2631556Srgrimes		pipenode->npipe.cmdlist = lp;
2641556Srgrimes		lp->n = n1;
2651556Srgrimes		do {
2661556Srgrimes			prev = lp;
2671556Srgrimes			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
2681556Srgrimes			lp->n = command();
2691556Srgrimes			prev->next = lp;
2701556Srgrimes		} while (readtoken() == TPIPE);
2711556Srgrimes		lp->next = NULL;
2721556Srgrimes		n1 = pipenode;
2731556Srgrimes	}
2741556Srgrimes	tokpushback++;
27575336Sbrian	if (negate) {
27675336Sbrian		n2 = (union node *)stalloc(sizeof (struct nnot));
27775336Sbrian		n2->type = NNOT;
27875336Sbrian		n2->nnot.com = n1;
27975336Sbrian		return n2;
28075336Sbrian	} else
28175336Sbrian		return n1;
2821556Srgrimes}
2831556Srgrimes
2841556Srgrimes
2851556Srgrimes
2861556SrgrimesSTATIC union node *
28790111Simpcommand(void)
28890111Simp{
2891556Srgrimes	union node *n1, *n2;
2901556Srgrimes	union node *ap, **app;
2911556Srgrimes	union node *cp, **cpp;
2921556Srgrimes	union node *redir, **rpp;
29375160Sbrian	int t, negate = 0;
2941556Srgrimes
2951556Srgrimes	checkkwd = 2;
29617987Speter	redir = NULL;
29717987Speter	n1 = NULL;
2981556Srgrimes	rpp = &redir;
29920425Ssteve
3001556Srgrimes	/* Check for redirection which may precede command */
3011556Srgrimes	while (readtoken() == TREDIR) {
3021556Srgrimes		*rpp = n2 = redirnode;
3031556Srgrimes		rpp = &n2->nfile.next;
3041556Srgrimes		parsefname();
3051556Srgrimes	}
3061556Srgrimes	tokpushback++;
3071556Srgrimes
30875160Sbrian	while (readtoken() == TNOT) {
30975160Sbrian		TRACE(("command: TNOT recognized\n"));
31075160Sbrian		negate = !negate;
31175160Sbrian	}
31275160Sbrian	tokpushback++;
31375160Sbrian
3141556Srgrimes	switch (readtoken()) {
3151556Srgrimes	case TIF:
3161556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nif));
3171556Srgrimes		n1->type = NIF;
318104554Stjr		if ((n1->nif.test = list(0)) == NULL)
319104554Stjr			synexpect(-1);
3201556Srgrimes		if (readtoken() != TTHEN)
3211556Srgrimes			synexpect(TTHEN);
3221556Srgrimes		n1->nif.ifpart = list(0);
3231556Srgrimes		n2 = n1;
3241556Srgrimes		while (readtoken() == TELIF) {
3251556Srgrimes			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
3261556Srgrimes			n2 = n2->nif.elsepart;
3271556Srgrimes			n2->type = NIF;
328104554Stjr			if ((n2->nif.test = list(0)) == NULL)
329104554Stjr				synexpect(-1);
3301556Srgrimes			if (readtoken() != TTHEN)
3311556Srgrimes				synexpect(TTHEN);
3321556Srgrimes			n2->nif.ifpart = list(0);
3331556Srgrimes		}
3341556Srgrimes		if (lasttoken == TELSE)
3351556Srgrimes			n2->nif.elsepart = list(0);
3361556Srgrimes		else {
3371556Srgrimes			n2->nif.elsepart = NULL;
3381556Srgrimes			tokpushback++;
3391556Srgrimes		}
3401556Srgrimes		if (readtoken() != TFI)
3411556Srgrimes			synexpect(TFI);
3421556Srgrimes		checkkwd = 1;
3431556Srgrimes		break;
3441556Srgrimes	case TWHILE:
3451556Srgrimes	case TUNTIL: {
3461556Srgrimes		int got;
3471556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nbinary));
3481556Srgrimes		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
349104554Stjr		if ((n1->nbinary.ch1 = list(0)) == NULL)
350104554Stjr			synexpect(-1);
3511556Srgrimes		if ((got=readtoken()) != TDO) {
3521556SrgrimesTRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
3531556Srgrimes			synexpect(TDO);
3541556Srgrimes		}
3551556Srgrimes		n1->nbinary.ch2 = list(0);
3561556Srgrimes		if (readtoken() != TDONE)
3571556Srgrimes			synexpect(TDONE);
3581556Srgrimes		checkkwd = 1;
3591556Srgrimes		break;
3601556Srgrimes	}
3611556Srgrimes	case TFOR:
3621556Srgrimes		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
3631556Srgrimes			synerror("Bad for loop variable");
3641556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nfor));
3651556Srgrimes		n1->type = NFOR;
3661556Srgrimes		n1->nfor.var = wordtext;
367199282Sjilles		while (readtoken() == TNL)
368199282Sjilles			;
369199282Sjilles		if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
3701556Srgrimes			app = &ap;
3711556Srgrimes			while (readtoken() == TWORD) {
3721556Srgrimes				n2 = (union node *)stalloc(sizeof (struct narg));
3731556Srgrimes				n2->type = NARG;
3741556Srgrimes				n2->narg.text = wordtext;
3751556Srgrimes				n2->narg.backquote = backquotelist;
3761556Srgrimes				*app = n2;
3771556Srgrimes				app = &n2->narg.next;
3781556Srgrimes			}
3791556Srgrimes			*app = NULL;
3801556Srgrimes			n1->nfor.args = ap;
3811556Srgrimes			if (lasttoken != TNL && lasttoken != TSEMI)
3821556Srgrimes				synexpect(-1);
3831556Srgrimes		} else {
384149096Sstefanf			static char argvars[5] = {
385149096Sstefanf				CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
386149096Sstefanf			};
3871556Srgrimes			n2 = (union node *)stalloc(sizeof (struct narg));
3881556Srgrimes			n2->type = NARG;
389149096Sstefanf			n2->narg.text = argvars;
3901556Srgrimes			n2->narg.backquote = NULL;
3911556Srgrimes			n2->narg.next = NULL;
3921556Srgrimes			n1->nfor.args = n2;
3931556Srgrimes			/*
3941556Srgrimes			 * Newline or semicolon here is optional (but note
3951556Srgrimes			 * that the original Bourne shell only allowed NL).
3961556Srgrimes			 */
3971556Srgrimes			if (lasttoken != TNL && lasttoken != TSEMI)
3981556Srgrimes				tokpushback++;
3991556Srgrimes		}
4001556Srgrimes		checkkwd = 2;
4011556Srgrimes		if ((t = readtoken()) == TDO)
4021556Srgrimes			t = TDONE;
4031556Srgrimes		else if (t == TBEGIN)
4041556Srgrimes			t = TEND;
4051556Srgrimes		else
4061556Srgrimes			synexpect(-1);
4071556Srgrimes		n1->nfor.body = list(0);
4081556Srgrimes		if (readtoken() != t)
4091556Srgrimes			synexpect(t);
4101556Srgrimes		checkkwd = 1;
4111556Srgrimes		break;
4121556Srgrimes	case TCASE:
4131556Srgrimes		n1 = (union node *)stalloc(sizeof (struct ncase));
4141556Srgrimes		n1->type = NCASE;
4151556Srgrimes		if (readtoken() != TWORD)
4161556Srgrimes			synexpect(TWORD);
4171556Srgrimes		n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
4181556Srgrimes		n2->type = NARG;
4191556Srgrimes		n2->narg.text = wordtext;
4201556Srgrimes		n2->narg.backquote = backquotelist;
4211556Srgrimes		n2->narg.next = NULL;
4221556Srgrimes		while (readtoken() == TNL);
4231556Srgrimes		if (lasttoken != TWORD || ! equal(wordtext, "in"))
4241556Srgrimes			synerror("expecting \"in\"");
4251556Srgrimes		cpp = &n1->ncase.cases;
42618018Speter		noaliases = 1;	/* turn off alias expansion */
4272760Ssef		checkkwd = 2, readtoken();
428104202Stjr		while (lasttoken != TESAC) {
4291556Srgrimes			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
4301556Srgrimes			cp->type = NCLIST;
4311556Srgrimes			app = &cp->nclist.pattern;
432104207Stjr			if (lasttoken == TLP)
433104207Stjr				readtoken();
4341556Srgrimes			for (;;) {
4351556Srgrimes				*app = ap = (union node *)stalloc(sizeof (struct narg));
4361556Srgrimes				ap->type = NARG;
4371556Srgrimes				ap->narg.text = wordtext;
4381556Srgrimes				ap->narg.backquote = backquotelist;
4392760Ssef				if (checkkwd = 2, readtoken() != TPIPE)
4401556Srgrimes					break;
4411556Srgrimes				app = &ap->narg.next;
4422760Ssef				readtoken();
4431556Srgrimes			}
4441556Srgrimes			ap->narg.next = NULL;
4451556Srgrimes			if (lasttoken != TRP)
44618018Speter				noaliases = 0, synexpect(TRP);
4471556Srgrimes			cp->nclist.body = list(0);
4482760Ssef
4492760Ssef			checkkwd = 2;
4502760Ssef			if ((t = readtoken()) != TESAC) {
4512760Ssef				if (t != TENDCASE)
45218018Speter					noaliases = 0, synexpect(TENDCASE);
4532760Ssef				else
4542760Ssef					checkkwd = 2, readtoken();
4552760Ssef			}
4561556Srgrimes			cpp = &cp->nclist.next;
457104202Stjr		}
45818018Speter		noaliases = 0;	/* reset alias expansion */
4591556Srgrimes		*cpp = NULL;
4601556Srgrimes		checkkwd = 1;
4611556Srgrimes		break;
4621556Srgrimes	case TLP:
4631556Srgrimes		n1 = (union node *)stalloc(sizeof (struct nredir));
4641556Srgrimes		n1->type = NSUBSHELL;
4651556Srgrimes		n1->nredir.n = list(0);
4661556Srgrimes		n1->nredir.redirect = NULL;
4671556Srgrimes		if (readtoken() != TRP)
4681556Srgrimes			synexpect(TRP);
4691556Srgrimes		checkkwd = 1;
4701556Srgrimes		break;
4711556Srgrimes	case TBEGIN:
4721556Srgrimes		n1 = list(0);
4731556Srgrimes		if (readtoken() != TEND)
4741556Srgrimes			synexpect(TEND);
4751556Srgrimes		checkkwd = 1;
4761556Srgrimes		break;
4771556Srgrimes	/* Handle an empty command like other simple commands.  */
47817987Speter	case TSEMI:
479101662Stjr	case TAND:
480101662Stjr	case TOR:
48117987Speter		/*
48217987Speter		 * An empty command before a ; doesn't make much sense, and
48317987Speter		 * should certainly be disallowed in the case of `if ;'.
48417987Speter		 */
48517987Speter		if (!redir)
48617987Speter			synexpect(-1);
4871556Srgrimes	case TNL:
48810399Sjoerg	case TEOF:
4891556Srgrimes	case TWORD:
49017987Speter	case TRP:
4911556Srgrimes		tokpushback++;
49275160Sbrian		n1 = simplecmd(rpp, redir);
49375160Sbrian		goto checkneg;
4941556Srgrimes	default:
4951556Srgrimes		synexpect(-1);
4961556Srgrimes	}
4971556Srgrimes
4981556Srgrimes	/* Now check for redirection which may follow command */
4991556Srgrimes	while (readtoken() == TREDIR) {
5001556Srgrimes		*rpp = n2 = redirnode;
5011556Srgrimes		rpp = &n2->nfile.next;
5021556Srgrimes		parsefname();
5031556Srgrimes	}
5041556Srgrimes	tokpushback++;
5051556Srgrimes	*rpp = NULL;
5061556Srgrimes	if (redir) {
5071556Srgrimes		if (n1->type != NSUBSHELL) {
5081556Srgrimes			n2 = (union node *)stalloc(sizeof (struct nredir));
5091556Srgrimes			n2->type = NREDIR;
5101556Srgrimes			n2->nredir.n = n1;
5111556Srgrimes			n1 = n2;
5121556Srgrimes		}
5131556Srgrimes		n1->nredir.redirect = redir;
5141556Srgrimes	}
51575160Sbrian
51675160Sbriancheckneg:
51775160Sbrian	if (negate) {
51875160Sbrian		n2 = (union node *)stalloc(sizeof (struct nnot));
51975160Sbrian		n2->type = NNOT;
52075160Sbrian		n2->nnot.com = n1;
52175160Sbrian		return n2;
52275160Sbrian	}
52375160Sbrian	else
52475160Sbrian		return n1;
5251556Srgrimes}
5261556Srgrimes
5271556Srgrimes
5281556SrgrimesSTATIC union node *
52990111Simpsimplecmd(union node **rpp, union node *redir)
53090111Simp{
5311556Srgrimes	union node *args, **app;
5321556Srgrimes	union node **orig_rpp = rpp;
53375160Sbrian	union node *n = NULL, *n2;
53475160Sbrian	int negate = 0;
5351556Srgrimes
5361556Srgrimes	/* If we don't have any redirections already, then we must reset */
5371556Srgrimes	/* rpp to be the address of the local redir variable.  */
5381556Srgrimes	if (redir == 0)
5391556Srgrimes		rpp = &redir;
5401556Srgrimes
5411556Srgrimes	args = NULL;
5421556Srgrimes	app = &args;
5438855Srgrimes	/*
5441556Srgrimes	 * We save the incoming value, because we need this for shell
5451556Srgrimes	 * functions.  There can not be a redirect or an argument between
5468855Srgrimes	 * the function name and the open parenthesis.
5471556Srgrimes	 */
5481556Srgrimes	orig_rpp = rpp;
5491556Srgrimes
55075160Sbrian	while (readtoken() == TNOT) {
55175160Sbrian		TRACE(("command: TNOT recognized\n"));
55275160Sbrian		negate = !negate;
55375160Sbrian	}
55475160Sbrian	tokpushback++;
55575160Sbrian
5561556Srgrimes	for (;;) {
5571556Srgrimes		if (readtoken() == TWORD) {
5581556Srgrimes			n = (union node *)stalloc(sizeof (struct narg));
5591556Srgrimes			n->type = NARG;
5601556Srgrimes			n->narg.text = wordtext;
5611556Srgrimes			n->narg.backquote = backquotelist;
5621556Srgrimes			*app = n;
5631556Srgrimes			app = &n->narg.next;
5641556Srgrimes		} else if (lasttoken == TREDIR) {
5651556Srgrimes			*rpp = n = redirnode;
5661556Srgrimes			rpp = &n->nfile.next;
5671556Srgrimes			parsefname();	/* read name of redirection file */
5681556Srgrimes		} else if (lasttoken == TLP && app == &args->narg.next
5691556Srgrimes					    && rpp == orig_rpp) {
5701556Srgrimes			/* We have a function */
5711556Srgrimes			if (readtoken() != TRP)
5721556Srgrimes				synexpect(TRP);
573179022Sstefanf			funclinno = plinno;
5741556Srgrimes#ifdef notdef
5751556Srgrimes			if (! goodname(n->narg.text))
5761556Srgrimes				synerror("Bad function name");
5771556Srgrimes#endif
5781556Srgrimes			n->type = NDEFUN;
5791556Srgrimes			n->narg.next = command();
580179022Sstefanf			funclinno = 0;
58175160Sbrian			goto checkneg;
5821556Srgrimes		} else {
5831556Srgrimes			tokpushback++;
5841556Srgrimes			break;
5851556Srgrimes		}
5861556Srgrimes	}
5871556Srgrimes	*app = NULL;
5881556Srgrimes	*rpp = NULL;
5891556Srgrimes	n = (union node *)stalloc(sizeof (struct ncmd));
5901556Srgrimes	n->type = NCMD;
5911556Srgrimes	n->ncmd.backgnd = 0;
5921556Srgrimes	n->ncmd.args = args;
5931556Srgrimes	n->ncmd.redirect = redir;
59475160Sbrian
59575160Sbriancheckneg:
59675160Sbrian	if (negate) {
59775160Sbrian		n2 = (union node *)stalloc(sizeof (struct nnot));
59875160Sbrian		n2->type = NNOT;
59975160Sbrian		n2->nnot.com = n;
60075160Sbrian		return n2;
60175160Sbrian	}
60275160Sbrian	else
60375160Sbrian		return n;
6041556Srgrimes}
6051556Srgrimes
60617987SpeterSTATIC union node *
60790111Simpmakename(void)
60890111Simp{
60917987Speter	union node *n;
6101556Srgrimes
61117987Speter	n = (union node *)stalloc(sizeof (struct narg));
61217987Speter	n->type = NARG;
61317987Speter	n->narg.next = NULL;
61417987Speter	n->narg.text = wordtext;
61517987Speter	n->narg.backquote = backquotelist;
61617987Speter	return n;
61717987Speter}
61817987Speter
61990111Simpvoid fixredir(union node *n, const char *text, int err)
62090111Simp{
62117987Speter	TRACE(("Fix redir %s %d\n", text, err));
62217987Speter	if (!err)
62317987Speter		n->ndup.vname = NULL;
62417987Speter
62517987Speter	if (is_digit(text[0]) && text[1] == '\0')
62617987Speter		n->ndup.dupfd = digit_val(text[0]);
62717987Speter	else if (text[0] == '-' && text[1] == '\0')
62817987Speter		n->ndup.dupfd = -1;
62917987Speter	else {
63020425Ssteve
63117987Speter		if (err)
63217987Speter			synerror("Bad fd number");
63317987Speter		else
63417987Speter			n->ndup.vname = makename();
63517987Speter	}
63617987Speter}
63717987Speter
63817987Speter
6391556SrgrimesSTATIC void
64090111Simpparsefname(void)
64190111Simp{
6421556Srgrimes	union node *n = redirnode;
6431556Srgrimes
6441556Srgrimes	if (readtoken() != TWORD)
6451556Srgrimes		synexpect(-1);
6461556Srgrimes	if (n->type == NHERE) {
6471556Srgrimes		struct heredoc *here = heredoc;
6481556Srgrimes		struct heredoc *p;
6491556Srgrimes		int i;
6501556Srgrimes
6511556Srgrimes		if (quoteflag == 0)
6521556Srgrimes			n->type = NXHERE;
6531556Srgrimes		TRACE(("Here document %d\n", n->type));
6541556Srgrimes		if (here->striptabs) {
6551556Srgrimes			while (*wordtext == '\t')
6561556Srgrimes				wordtext++;
6571556Srgrimes		}
6581556Srgrimes		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
6591556Srgrimes			synerror("Illegal eof marker for << redirection");
6601556Srgrimes		rmescapes(wordtext);
6611556Srgrimes		here->eofmark = wordtext;
6621556Srgrimes		here->next = NULL;
6631556Srgrimes		if (heredoclist == NULL)
6641556Srgrimes			heredoclist = here;
6651556Srgrimes		else {
6661556Srgrimes			for (p = heredoclist ; p->next ; p = p->next);
6671556Srgrimes			p->next = here;
6681556Srgrimes		}
6691556Srgrimes	} else if (n->type == NTOFD || n->type == NFROMFD) {
67017987Speter		fixredir(n, wordtext, 0);
6711556Srgrimes	} else {
67217987Speter		n->nfile.fname = makename();
6731556Srgrimes	}
6741556Srgrimes}
6751556Srgrimes
6761556Srgrimes
6771556Srgrimes/*
6781556Srgrimes * Input any here documents.
6791556Srgrimes */
6801556Srgrimes
6811556SrgrimesSTATIC void
68290111Simpparseheredoc(void)
68390111Simp{
6841556Srgrimes	struct heredoc *here;
6851556Srgrimes	union node *n;
6861556Srgrimes
6871556Srgrimes	while (heredoclist) {
6881556Srgrimes		here = heredoclist;
6891556Srgrimes		heredoclist = here->next;
6901556Srgrimes		if (needprompt) {
6911556Srgrimes			setprompt(2);
6921556Srgrimes			needprompt = 0;
6931556Srgrimes		}
6941556Srgrimes		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
6951556Srgrimes				here->eofmark, here->striptabs);
6961556Srgrimes		n = (union node *)stalloc(sizeof (struct narg));
6971556Srgrimes		n->narg.type = NARG;
6981556Srgrimes		n->narg.next = NULL;
6991556Srgrimes		n->narg.text = wordtext;
7001556Srgrimes		n->narg.backquote = backquotelist;
7011556Srgrimes		here->here->nhere.doc = n;
7021556Srgrimes	}
7031556Srgrimes}
7041556Srgrimes
7051556SrgrimesSTATIC int
70690111Simppeektoken(void)
70790111Simp{
7081556Srgrimes	int t;
7091556Srgrimes
7101556Srgrimes	t = readtoken();
7111556Srgrimes	tokpushback++;
7121556Srgrimes	return (t);
7131556Srgrimes}
7141556Srgrimes
7151556SrgrimesSTATIC int
71690111Simpreadtoken(void)
71790111Simp{
7181556Srgrimes	int t;
7191556Srgrimes	int savecheckkwd = checkkwd;
7201556Srgrimes	struct alias *ap;
7211556Srgrimes#ifdef DEBUG
7221556Srgrimes	int alreadyseen = tokpushback;
7231556Srgrimes#endif
7248855Srgrimes
7251556Srgrimes	top:
7261556Srgrimes	t = xxreadtoken();
7271556Srgrimes
7281556Srgrimes	if (checkkwd) {
7291556Srgrimes		/*
7301556Srgrimes		 * eat newlines
7311556Srgrimes		 */
7321556Srgrimes		if (checkkwd == 2) {
7331556Srgrimes			checkkwd = 0;
7341556Srgrimes			while (t == TNL) {
7351556Srgrimes				parseheredoc();
7361556Srgrimes				t = xxreadtoken();
7371556Srgrimes			}
7381556Srgrimes		} else
7391556Srgrimes			checkkwd = 0;
7401556Srgrimes		/*
7411556Srgrimes		 * check for keywords and aliases
7421556Srgrimes		 */
74320425Ssteve		if (t == TWORD && !quoteflag)
74417987Speter		{
74598463Sjmallett			const char * const *pp;
7461556Srgrimes
74798463Sjmallett			for (pp = parsekwd; *pp; pp++) {
74820425Ssteve				if (**pp == *wordtext && equal(*pp, wordtext))
74917987Speter				{
7501556Srgrimes					lasttoken = t = pp - parsekwd + KWDOFFSET;
7511556Srgrimes					TRACE(("keyword %s recognized\n", tokname[t]));
7521556Srgrimes					goto out;
7531556Srgrimes				}
7541556Srgrimes			}
75518018Speter			if (noaliases == 0 &&
75618018Speter			    (ap = lookupalias(wordtext, 1)) != NULL) {
7571556Srgrimes				pushstring(ap->val, strlen(ap->val), ap);
7581556Srgrimes				checkkwd = savecheckkwd;
7591556Srgrimes				goto top;
7601556Srgrimes			}
7611556Srgrimes		}
7621556Srgrimesout:
76375160Sbrian		checkkwd = (t == TNOT) ? savecheckkwd : 0;
7641556Srgrimes	}
7651556Srgrimes#ifdef DEBUG
7661556Srgrimes	if (!alreadyseen)
7671556Srgrimes	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
7681556Srgrimes	else
7691556Srgrimes	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
7701556Srgrimes#endif
7711556Srgrimes	return (t);
7721556Srgrimes}
7731556Srgrimes
7741556Srgrimes
7751556Srgrimes/*
7761556Srgrimes * Read the next input token.
7771556Srgrimes * If the token is a word, we set backquotelist to the list of cmds in
7781556Srgrimes *	backquotes.  We set quoteflag to true if any part of the word was
7791556Srgrimes *	quoted.
7801556Srgrimes * If the token is TREDIR, then we set redirnode to a structure containing
7811556Srgrimes *	the redirection.
7821556Srgrimes * In all cases, the variable startlinno is set to the number of the line
7831556Srgrimes *	on which the token starts.
7841556Srgrimes *
7851556Srgrimes * [Change comment:  here documents and internal procedures]
7861556Srgrimes * [Readtoken shouldn't have any arguments.  Perhaps we should make the
7871556Srgrimes *  word parsing code into a separate routine.  In this case, readtoken
7881556Srgrimes *  doesn't need to have any internal procedures, but parseword does.
7891556Srgrimes *  We could also make parseoperator in essence the main routine, and
7901556Srgrimes *  have parseword (readtoken1?) handle both words and redirection.]
7911556Srgrimes */
7921556Srgrimes
7931556Srgrimes#define RETURN(token)	return lasttoken = token
7941556Srgrimes
7951556SrgrimesSTATIC int
79690111Simpxxreadtoken(void)
79790111Simp{
79825230Ssteve	int c;
7991556Srgrimes
8001556Srgrimes	if (tokpushback) {
8011556Srgrimes		tokpushback = 0;
8021556Srgrimes		return lasttoken;
8031556Srgrimes	}
8041556Srgrimes	if (needprompt) {
8051556Srgrimes		setprompt(2);
8061556Srgrimes		needprompt = 0;
8071556Srgrimes	}
8081556Srgrimes	startlinno = plinno;
8091556Srgrimes	for (;;) {	/* until token or start of word found */
8101556Srgrimes		c = pgetc_macro();
8111556Srgrimes		if (c == ' ' || c == '\t')
8121556Srgrimes			continue;		/* quick check for white space first */
8131556Srgrimes		switch (c) {
8141556Srgrimes		case ' ': case '\t':
8151556Srgrimes			continue;
8161556Srgrimes		case '#':
8171556Srgrimes			while ((c = pgetc()) != '\n' && c != PEOF);
8181556Srgrimes			pungetc();
8191556Srgrimes			continue;
8201556Srgrimes		case '\\':
8211556Srgrimes			if (pgetc() == '\n') {
8221556Srgrimes				startlinno = ++plinno;
8231556Srgrimes				if (doprompt)
8241556Srgrimes					setprompt(2);
8251556Srgrimes				else
8261556Srgrimes					setprompt(0);
8271556Srgrimes				continue;
8281556Srgrimes			}
8291556Srgrimes			pungetc();
8301556Srgrimes			goto breakloop;
8311556Srgrimes		case '\n':
8321556Srgrimes			plinno++;
8331556Srgrimes			needprompt = doprompt;
8341556Srgrimes			RETURN(TNL);
8351556Srgrimes		case PEOF:
8361556Srgrimes			RETURN(TEOF);
8371556Srgrimes		case '&':
8381556Srgrimes			if (pgetc() == '&')
8391556Srgrimes				RETURN(TAND);
8401556Srgrimes			pungetc();
8411556Srgrimes			RETURN(TBACKGND);
8421556Srgrimes		case '|':
8431556Srgrimes			if (pgetc() == '|')
8441556Srgrimes				RETURN(TOR);
8451556Srgrimes			pungetc();
8461556Srgrimes			RETURN(TPIPE);
8471556Srgrimes		case ';':
8481556Srgrimes			if (pgetc() == ';')
8491556Srgrimes				RETURN(TENDCASE);
8501556Srgrimes			pungetc();
8511556Srgrimes			RETURN(TSEMI);
8521556Srgrimes		case '(':
8531556Srgrimes			RETURN(TLP);
8541556Srgrimes		case ')':
8551556Srgrimes			RETURN(TRP);
8561556Srgrimes		default:
8571556Srgrimes			goto breakloop;
8581556Srgrimes		}
8591556Srgrimes	}
8601556Srgrimesbreakloop:
8611556Srgrimes	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
8621556Srgrimes#undef RETURN
8631556Srgrimes}
8641556Srgrimes
8651556Srgrimes
866205130Sjilles/*
867205130Sjilles * Called to parse command substitutions.
868205130Sjilles */
8691556Srgrimes
870205130SjillesSTATIC char *
871205130Sjillesparsebackq(char *out, struct nodelist **pbqlist,
872205130Sjilles		int oldstyle, int dblquote, int quoted)
873205130Sjilles{
874205130Sjilles	struct nodelist **nlpp;
875205130Sjilles	union node *n;
876205130Sjilles	char *volatile str;
877205130Sjilles	struct jmploc jmploc;
878205130Sjilles	struct jmploc *const savehandler = handler;
879205130Sjilles	int savelen;
880205130Sjilles	int saveprompt;
881205130Sjilles	const int bq_startlinno = plinno;
882205130Sjilles	char *volatile ostr = NULL;
883205130Sjilles	struct parsefile *const savetopfile = getcurrentfile();
884205130Sjilles
885205130Sjilles	str = NULL;
886205130Sjilles	if (setjmp(jmploc.loc)) {
887205130Sjilles		popfilesupto(savetopfile);
888205130Sjilles		if (str)
889205130Sjilles			ckfree(str);
890205130Sjilles		if (ostr)
891205130Sjilles			ckfree(ostr);
892205130Sjilles		handler = savehandler;
893205130Sjilles		if (exception == EXERROR) {
894205130Sjilles			startlinno = bq_startlinno;
895205130Sjilles			synerror("Error in command substitution");
896205130Sjilles		}
897205130Sjilles		longjmp(handler->loc, 1);
898205130Sjilles	}
899205130Sjilles	INTOFF;
900205130Sjilles	savelen = out - stackblock();
901205130Sjilles	if (savelen > 0) {
902205130Sjilles		str = ckmalloc(savelen);
903205130Sjilles		memcpy(str, stackblock(), savelen);
904205130Sjilles	}
905205130Sjilles	handler = &jmploc;
906205130Sjilles	INTON;
907205130Sjilles        if (oldstyle) {
908205130Sjilles                /* We must read until the closing backquote, giving special
909205130Sjilles                   treatment to some slashes, and then push the string and
910205130Sjilles                   reread it as input, interpreting it normally.  */
911205130Sjilles                char *oout;
912205130Sjilles                int c;
913205130Sjilles                int olen;
914205130Sjilles
915205130Sjilles
916205130Sjilles                STARTSTACKSTR(oout);
917205130Sjilles		for (;;) {
918205130Sjilles			if (needprompt) {
919205130Sjilles				setprompt(2);
920205130Sjilles				needprompt = 0;
921205130Sjilles			}
922205130Sjilles			switch (c = pgetc()) {
923205130Sjilles			case '`':
924205130Sjilles				goto done;
925205130Sjilles
926205130Sjilles			case '\\':
927205130Sjilles                                if ((c = pgetc()) == '\n') {
928205130Sjilles					plinno++;
929205130Sjilles					if (doprompt)
930205130Sjilles						setprompt(2);
931205130Sjilles					else
932205130Sjilles						setprompt(0);
933205130Sjilles					/*
934205130Sjilles					 * If eating a newline, avoid putting
935205130Sjilles					 * the newline into the new character
936205130Sjilles					 * stream (via the STPUTC after the
937205130Sjilles					 * switch).
938205130Sjilles					 */
939205130Sjilles					continue;
940205130Sjilles				}
941205130Sjilles                                if (c != '\\' && c != '`' && c != '$'
942205130Sjilles                                    && (!dblquote || c != '"'))
943205130Sjilles                                        STPUTC('\\', oout);
944205130Sjilles				break;
945205130Sjilles
946205130Sjilles			case '\n':
947205130Sjilles				plinno++;
948205130Sjilles				needprompt = doprompt;
949205130Sjilles				break;
950205130Sjilles
951205130Sjilles			case PEOF:
952205130Sjilles			        startlinno = plinno;
953205130Sjilles				synerror("EOF in backquote substitution");
954205130Sjilles 				break;
955205130Sjilles
956205130Sjilles			default:
957205130Sjilles				break;
958205130Sjilles			}
959205130Sjilles			STPUTC(c, oout);
960205130Sjilles                }
961205130Sjillesdone:
962205130Sjilles                STPUTC('\0', oout);
963205130Sjilles                olen = oout - stackblock();
964205130Sjilles		INTOFF;
965205130Sjilles		ostr = ckmalloc(olen);
966205130Sjilles		memcpy(ostr, stackblock(), olen);
967205130Sjilles		setinputstring(ostr, 1);
968205130Sjilles		INTON;
969205130Sjilles        }
970205130Sjilles	nlpp = pbqlist;
971205130Sjilles	while (*nlpp)
972205130Sjilles		nlpp = &(*nlpp)->next;
973205130Sjilles	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
974205130Sjilles	(*nlpp)->next = NULL;
975205130Sjilles
976205130Sjilles	if (oldstyle) {
977205130Sjilles		saveprompt = doprompt;
978205130Sjilles		doprompt = 0;
979205130Sjilles	}
980205130Sjilles
981205130Sjilles	n = list(0);
982205130Sjilles
983205130Sjilles	if (oldstyle)
984205130Sjilles		doprompt = saveprompt;
985205130Sjilles	else {
986205130Sjilles		if (readtoken() != TRP)
987205130Sjilles			synexpect(TRP);
988205130Sjilles	}
989205130Sjilles
990205130Sjilles	(*nlpp)->n = n;
991205130Sjilles        if (oldstyle) {
992205130Sjilles		/*
993205130Sjilles		 * Start reading from old file again, ignoring any pushed back
994205130Sjilles		 * tokens left from the backquote parsing
995205130Sjilles		 */
996205130Sjilles                popfile();
997205130Sjilles		tokpushback = 0;
998205130Sjilles	}
999205130Sjilles	while (stackblocksize() <= savelen)
1000205130Sjilles		growstackblock();
1001205130Sjilles	STARTSTACKSTR(out);
1002205130Sjilles	if (str) {
1003205130Sjilles		memcpy(out, str, savelen);
1004205130Sjilles		STADJUST(savelen, out);
1005205130Sjilles		INTOFF;
1006205130Sjilles		ckfree(str);
1007205130Sjilles		str = NULL;
1008205130Sjilles		INTON;
1009205130Sjilles	}
1010205130Sjilles	if (ostr) {
1011205130Sjilles		INTOFF;
1012205130Sjilles		ckfree(ostr);
1013205130Sjilles		ostr = NULL;
1014205130Sjilles		INTON;
1015205130Sjilles	}
1016205130Sjilles	handler = savehandler;
1017205130Sjilles	if (quoted)
1018205130Sjilles		USTPUTC(CTLBACKQ | CTLQUOTE, out);
1019205130Sjilles	else
1020205130Sjilles		USTPUTC(CTLBACKQ, out);
1021205130Sjilles	return out;
1022205130Sjilles}
1023205130Sjilles
1024205130Sjilles
10251556Srgrimes/*
10261556Srgrimes * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
10271556Srgrimes * is not NULL, read a here document.  In the latter case, eofmark is the
10281556Srgrimes * word which marks the end of the document and striptabs is true if
10291556Srgrimes * leading tabs should be stripped from the document.  The argument firstc
10301556Srgrimes * is the first character of the input token or document.
10311556Srgrimes *
10321556Srgrimes * Because C does not have internal subroutines, I have simulated them
10331556Srgrimes * using goto's to implement the subroutine linkage.  The following macros
10341556Srgrimes * will run code that appears at the end of readtoken1.
10351556Srgrimes */
10361556Srgrimes
10371556Srgrimes#define CHECKEND()	{goto checkend; checkend_return:;}
10381556Srgrimes#define PARSEREDIR()	{goto parseredir; parseredir_return:;}
10391556Srgrimes#define PARSESUB()	{goto parsesub; parsesub_return:;}
10401556Srgrimes#define	PARSEARITH()	{goto parsearith; parsearith_return:;}
10411556Srgrimes
10421556SrgrimesSTATIC int
104390111Simpreadtoken1(int firstc, char const *syntax, char *eofmark, int striptabs)
104490111Simp{
104517987Speter	int c = firstc;
104617987Speter	char *out;
10471556Srgrimes	int len;
10481556Srgrimes	char line[EOFMARKLEN + 1];
10491556Srgrimes	struct nodelist *bqlist;
10501556Srgrimes	int quotef;
10511556Srgrimes	int dblquote;
10521556Srgrimes	int varnest;	/* levels of variables expansion */
10531556Srgrimes	int arinest;	/* levels of arithmetic expansion */
10541556Srgrimes	int parenlevel;	/* levels of parens in arithmetic */
10551556Srgrimes	char const *prevsyntax;	/* syntax before arithmetic */
105654679Scracauer	int synentry;
10571556Srgrimes
10581556Srgrimes	startlinno = plinno;
10591556Srgrimes	dblquote = 0;
10601556Srgrimes	if (syntax == DQSYNTAX)
10611556Srgrimes		dblquote = 1;
10621556Srgrimes	quotef = 0;
10631556Srgrimes	bqlist = NULL;
10641556Srgrimes	varnest = 0;
10651556Srgrimes	arinest = 0;
10661556Srgrimes	parenlevel = 0;
10671556Srgrimes
10681556Srgrimes	STARTSTACKSTR(out);
10691556Srgrimes	loop: {	/* for each line, until end of word */
10701556Srgrimes		CHECKEND();	/* set c to PEOF if at end of here document */
10711556Srgrimes		for (;;) {	/* until end of line or end of word */
10721556Srgrimes			CHECKSTRSPACE(3, out);	/* permit 3 calls to USTPUTC */
107354679Scracauer
107464705Scracauer			synentry = syntax[c];
107554679Scracauer
107654679Scracauer			switch(synentry) {
10771556Srgrimes			case CNL:	/* '\n' */
10781556Srgrimes				if (syntax == BASESYNTAX)
10791556Srgrimes					goto endword;	/* exit outer loop */
10801556Srgrimes				USTPUTC(c, out);
10811556Srgrimes				plinno++;
10821556Srgrimes				if (doprompt)
10831556Srgrimes					setprompt(2);
10841556Srgrimes				else
10851556Srgrimes					setprompt(0);
10861556Srgrimes				c = pgetc();
10871556Srgrimes				goto loop;		/* continue outer loop */
10881556Srgrimes			case CWORD:
10891556Srgrimes				USTPUTC(c, out);
10901556Srgrimes				break;
10911556Srgrimes			case CCTL:
10921556Srgrimes				if (eofmark == NULL || dblquote)
10931556Srgrimes					USTPUTC(CTLESC, out);
10941556Srgrimes				USTPUTC(c, out);
10951556Srgrimes				break;
10961556Srgrimes			case CBACK:	/* backslash */
10971556Srgrimes				c = pgetc();
10981556Srgrimes				if (c == PEOF) {
10991556Srgrimes					USTPUTC('\\', out);
11001556Srgrimes					pungetc();
11011556Srgrimes				} else if (c == '\n') {
1102160849Syar					plinno++;
11031556Srgrimes					if (doprompt)
11041556Srgrimes						setprompt(2);
11051556Srgrimes					else
11061556Srgrimes						setprompt(0);
11071556Srgrimes				} else {
110854631Scracauer					if (dblquote && c != '\\' &&
110954631Scracauer					    c != '`' && c != '$' &&
111054631Scracauer					    (c != '"' || eofmark != NULL))
11111556Srgrimes						USTPUTC('\\', out);
111283675Stegge					if (SQSYNTAX[c] == CCTL)
11131556Srgrimes						USTPUTC(CTLESC, out);
111439137Stegge					else if (eofmark == NULL)
111538887Stegge						USTPUTC(CTLQUOTEMARK, out);
11161556Srgrimes					USTPUTC(c, out);
11171556Srgrimes					quotef++;
11181556Srgrimes				}
11191556Srgrimes				break;
11201556Srgrimes			case CSQUOTE:
112139137Stegge				if (eofmark == NULL)
112239137Stegge					USTPUTC(CTLQUOTEMARK, out);
11231556Srgrimes				syntax = SQSYNTAX;
11241556Srgrimes				break;
11251556Srgrimes			case CDQUOTE:
112639137Stegge				if (eofmark == NULL)
112739137Stegge					USTPUTC(CTLQUOTEMARK, out);
11281556Srgrimes				syntax = DQSYNTAX;
11291556Srgrimes				dblquote = 1;
11301556Srgrimes				break;
11311556Srgrimes			case CENDQUOTE:
113239137Stegge				if (eofmark != NULL && arinest == 0 &&
113339137Stegge				    varnest == 0) {
11341556Srgrimes					USTPUTC(c, out);
11351556Srgrimes				} else {
113639137Stegge					if (arinest) {
11371556Srgrimes						syntax = ARISYNTAX;
113839137Stegge						dblquote = 0;
113939137Stegge					} else if (eofmark == NULL) {
11401556Srgrimes						syntax = BASESYNTAX;
114139137Stegge						dblquote = 0;
114239137Stegge					}
11431556Srgrimes					quotef++;
11441556Srgrimes				}
11451556Srgrimes				break;
11461556Srgrimes			case CVAR:	/* '$' */
11471556Srgrimes				PARSESUB();		/* parse substitution */
11481556Srgrimes				break;
11491556Srgrimes			case CENDVAR:	/* '}' */
11501556Srgrimes				if (varnest > 0) {
11511556Srgrimes					varnest--;
11521556Srgrimes					USTPUTC(CTLENDVAR, out);
11531556Srgrimes				} else {
11541556Srgrimes					USTPUTC(c, out);
11551556Srgrimes				}
11561556Srgrimes				break;
11571556Srgrimes			case CLP:	/* '(' in arithmetic */
11581556Srgrimes				parenlevel++;
11591556Srgrimes				USTPUTC(c, out);
11601556Srgrimes				break;
11611556Srgrimes			case CRP:	/* ')' in arithmetic */
11621556Srgrimes				if (parenlevel > 0) {
11631556Srgrimes					USTPUTC(c, out);
11641556Srgrimes					--parenlevel;
11651556Srgrimes				} else {
11661556Srgrimes					if (pgetc() == ')') {
11671556Srgrimes						if (--arinest == 0) {
11681556Srgrimes							USTPUTC(CTLENDARI, out);
11691556Srgrimes							syntax = prevsyntax;
117039137Stegge							if (syntax == DQSYNTAX)
117139137Stegge								dblquote = 1;
117239137Stegge							else
117339137Stegge								dblquote = 0;
11741556Srgrimes						} else
11751556Srgrimes							USTPUTC(')', out);
11761556Srgrimes					} else {
11778855Srgrimes						/*
11781556Srgrimes						 * unbalanced parens
11791556Srgrimes						 *  (don't 2nd guess - no error)
11801556Srgrimes						 */
11811556Srgrimes						pungetc();
11821556Srgrimes						USTPUTC(')', out);
11831556Srgrimes					}
11841556Srgrimes				}
11851556Srgrimes				break;
11861556Srgrimes			case CBQUOTE:	/* '`' */
1187205130Sjilles				out = parsebackq(out, &bqlist, 1, dblquote,
1188205130Sjilles						arinest || dblquote);
11891556Srgrimes				break;
11901556Srgrimes			case CEOF:
11911556Srgrimes				goto endword;		/* exit outer loop */
11921556Srgrimes			default:
11931556Srgrimes				if (varnest == 0)
11941556Srgrimes					goto endword;	/* exit outer loop */
11951556Srgrimes				USTPUTC(c, out);
11961556Srgrimes			}
11971556Srgrimes			c = pgetc_macro();
11981556Srgrimes		}
11991556Srgrimes	}
12001556Srgrimesendword:
12011556Srgrimes	if (syntax == ARISYNTAX)
12021556Srgrimes		synerror("Missing '))'");
1203197691Sjilles	if (syntax != BASESYNTAX && eofmark == NULL)
12041556Srgrimes		synerror("Unterminated quoted string");
12051556Srgrimes	if (varnest != 0) {
12061556Srgrimes		startlinno = plinno;
12071556Srgrimes		synerror("Missing '}'");
12081556Srgrimes	}
12091556Srgrimes	USTPUTC('\0', out);
12101556Srgrimes	len = out - stackblock();
12111556Srgrimes	out = stackblock();
12121556Srgrimes	if (eofmark == NULL) {
12131556Srgrimes		if ((c == '>' || c == '<')
12141556Srgrimes		 && quotef == 0
12151556Srgrimes		 && len <= 2
12161556Srgrimes		 && (*out == '\0' || is_digit(*out))) {
12171556Srgrimes			PARSEREDIR();
12181556Srgrimes			return lasttoken = TREDIR;
12191556Srgrimes		} else {
12201556Srgrimes			pungetc();
12211556Srgrimes		}
12221556Srgrimes	}
12231556Srgrimes	quoteflag = quotef;
12241556Srgrimes	backquotelist = bqlist;
12251556Srgrimes	grabstackblock(len);
12261556Srgrimes	wordtext = out;
12271556Srgrimes	return lasttoken = TWORD;
12281556Srgrimes/* end of readtoken routine */
12291556Srgrimes
12301556Srgrimes
12311556Srgrimes
12321556Srgrimes/*
12331556Srgrimes * Check to see whether we are at the end of the here document.  When this
12341556Srgrimes * is called, c is set to the first character of the next input line.  If
12351556Srgrimes * we are at the end of the here document, this routine sets the c to PEOF.
12361556Srgrimes */
12371556Srgrimes
12381556Srgrimescheckend: {
12391556Srgrimes	if (eofmark) {
12401556Srgrimes		if (striptabs) {
12411556Srgrimes			while (c == '\t')
12421556Srgrimes				c = pgetc();
12431556Srgrimes		}
12441556Srgrimes		if (c == *eofmark) {
12451556Srgrimes			if (pfgets(line, sizeof line) != NULL) {
124625230Ssteve				char *p, *q;
12471556Srgrimes
12481556Srgrimes				p = line;
12491556Srgrimes				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
12501556Srgrimes				if (*p == '\n' && *q == '\0') {
12511556Srgrimes					c = PEOF;
12521556Srgrimes					plinno++;
12531556Srgrimes					needprompt = doprompt;
12541556Srgrimes				} else {
12551556Srgrimes					pushstring(line, strlen(line), NULL);
12561556Srgrimes				}
12571556Srgrimes			}
12581556Srgrimes		}
12591556Srgrimes	}
12601556Srgrimes	goto checkend_return;
12611556Srgrimes}
12621556Srgrimes
12631556Srgrimes
12641556Srgrimes/*
12651556Srgrimes * Parse a redirection operator.  The variable "out" points to a string
12661556Srgrimes * specifying the fd to be redirected.  The variable "c" contains the
12671556Srgrimes * first character of the redirection operator.
12681556Srgrimes */
12691556Srgrimes
12701556Srgrimesparseredir: {
12711556Srgrimes	char fd = *out;
12721556Srgrimes	union node *np;
12731556Srgrimes
12741556Srgrimes	np = (union node *)stalloc(sizeof (struct nfile));
12751556Srgrimes	if (c == '>') {
12761556Srgrimes		np->nfile.fd = 1;
12771556Srgrimes		c = pgetc();
12781556Srgrimes		if (c == '>')
12791556Srgrimes			np->type = NAPPEND;
12801556Srgrimes		else if (c == '&')
12811556Srgrimes			np->type = NTOFD;
128296922Stjr		else if (c == '|')
128396922Stjr			np->type = NCLOBBER;
12841556Srgrimes		else {
12851556Srgrimes			np->type = NTO;
12861556Srgrimes			pungetc();
12871556Srgrimes		}
12881556Srgrimes	} else {	/* c == '<' */
12891556Srgrimes		np->nfile.fd = 0;
12901556Srgrimes		c = pgetc();
12911556Srgrimes		if (c == '<') {
12921556Srgrimes			if (sizeof (struct nfile) != sizeof (struct nhere)) {
12931556Srgrimes				np = (union node *)stalloc(sizeof (struct nhere));
12941556Srgrimes				np->nfile.fd = 0;
12951556Srgrimes			}
12961556Srgrimes			np->type = NHERE;
12971556Srgrimes			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
12981556Srgrimes			heredoc->here = np;
12991556Srgrimes			if ((c = pgetc()) == '-') {
13001556Srgrimes				heredoc->striptabs = 1;
13011556Srgrimes			} else {
13021556Srgrimes				heredoc->striptabs = 0;
13031556Srgrimes				pungetc();
13041556Srgrimes			}
13051556Srgrimes		} else if (c == '&')
13061556Srgrimes			np->type = NFROMFD;
130766612Sbrian		else if (c == '>')
130866612Sbrian			np->type = NFROMTO;
13091556Srgrimes		else {
13101556Srgrimes			np->type = NFROM;
13111556Srgrimes			pungetc();
13121556Srgrimes		}
13131556Srgrimes	}
13141556Srgrimes	if (fd != '\0')
13151556Srgrimes		np->nfile.fd = digit_val(fd);
13161556Srgrimes	redirnode = np;
13171556Srgrimes	goto parseredir_return;
13181556Srgrimes}
13191556Srgrimes
13201556Srgrimes
13211556Srgrimes/*
13221556Srgrimes * Parse a substitution.  At this point, we have read the dollar sign
13231556Srgrimes * and nothing else.
13241556Srgrimes */
13251556Srgrimes
13261556Srgrimesparsesub: {
1327179022Sstefanf	char buf[10];
13281556Srgrimes	int subtype;
13291556Srgrimes	int typeloc;
13301556Srgrimes	int flags;
13311556Srgrimes	char *p;
13321556Srgrimes	static const char types[] = "}-+?=";
1333179022Sstefanf	int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1334179022Sstefanf	int i;
1335179022Sstefanf	int linno;
1336179387Sstefanf	int length;
13371556Srgrimes
13381556Srgrimes	c = pgetc();
1339149026Sstefanf	if (c != '(' && c != '{' && (is_eof(c) || !is_name(c)) &&
1340149026Sstefanf	    !is_special(c)) {
13411556Srgrimes		USTPUTC('$', out);
13421556Srgrimes		pungetc();
13431556Srgrimes	} else if (c == '(') {	/* $(command) or $((arith)) */
13441556Srgrimes		if (pgetc() == '(') {
13451556Srgrimes			PARSEARITH();
13461556Srgrimes		} else {
13471556Srgrimes			pungetc();
1348205130Sjilles			out = parsebackq(out, &bqlist, 0, dblquote,
1349205130Sjilles					arinest || dblquote);
13501556Srgrimes		}
13511556Srgrimes	} else {
13521556Srgrimes		USTPUTC(CTLVAR, out);
13531556Srgrimes		typeloc = out - stackblock();
13541556Srgrimes		USTPUTC(VSNORMAL, out);
13551556Srgrimes		subtype = VSNORMAL;
1356179022Sstefanf		flags = 0;
13571556Srgrimes		if (c == '{') {
135818202Speter			bracketed_name = 1;
13591556Srgrimes			c = pgetc();
136017987Speter			if (c == '#') {
136117987Speter				if ((c = pgetc()) == '}')
136217987Speter					c = '#';
136317987Speter				else
136417987Speter					subtype = VSLENGTH;
136517987Speter			}
136617987Speter			else
136717987Speter				subtype = 0;
13681556Srgrimes		}
1369149026Sstefanf		if (!is_eof(c) && is_name(c)) {
1370179387Sstefanf			length = 0;
13711556Srgrimes			do {
13721556Srgrimes				STPUTC(c, out);
13731556Srgrimes				c = pgetc();
1374179387Sstefanf				length++;
1375149026Sstefanf			} while (!is_eof(c) && is_in_name(c));
1376179387Sstefanf			if (length == 6 &&
1377179387Sstefanf			    strncmp(out - length, "LINENO", length) == 0) {
1378179022Sstefanf				/* Replace the variable name with the
1379179022Sstefanf				 * current line number. */
1380179022Sstefanf				linno = plinno;
1381179022Sstefanf				if (funclinno != 0)
1382179022Sstefanf					linno -= funclinno - 1;
1383179022Sstefanf				snprintf(buf, sizeof(buf), "%d", linno);
1384179022Sstefanf				STADJUST(-6, out);
1385179022Sstefanf				for (i = 0; buf[i] != '\0'; i++)
1386179022Sstefanf					STPUTC(buf[i], out);
1387179022Sstefanf				flags |= VSLINENO;
1388179022Sstefanf			}
138918202Speter		} else if (is_digit(c)) {
139018202Speter			if (bracketed_name) {
139118202Speter				do {
139218202Speter					STPUTC(c, out);
139318202Speter					c = pgetc();
139418202Speter				} while (is_digit(c));
139518202Speter			} else {
139618202Speter				STPUTC(c, out);
139718202Speter				c = pgetc();
139818202Speter			}
13991556Srgrimes		} else {
1400164003Sstefanf			if (! is_special(c)) {
1401164003Sstefanf				subtype = VSERROR;
1402164003Sstefanf				if (c == '}')
1403164003Sstefanf					pungetc();
1404206144Sjilles				else if (c == '\n' || c == PEOF)
1405206144Sjilles					synerror("Unexpected end of line in substitution");
1406164003Sstefanf				else
1407164003Sstefanf					USTPUTC(c, out);
1408164003Sstefanf			} else {
1409164003Sstefanf				USTPUTC(c, out);
1410164003Sstefanf				c = pgetc();
1411164003Sstefanf			}
14121556Srgrimes		}
14131556Srgrimes		if (subtype == 0) {
141417987Speter			switch (c) {
141517987Speter			case ':':
1416179022Sstefanf				flags |= VSNUL;
14171556Srgrimes				c = pgetc();
141817987Speter				/*FALLTHROUGH*/
141917987Speter			default:
142017987Speter				p = strchr(types, c);
1421164003Sstefanf				if (p == NULL) {
1422206144Sjilles					if (c == '\n' || c == PEOF)
1423206144Sjilles						synerror("Unexpected end of line in substitution");
1424164003Sstefanf					if (flags == VSNUL)
1425164003Sstefanf						STPUTC(':', out);
1426164003Sstefanf					STPUTC(c, out);
1427164003Sstefanf					subtype = VSERROR;
1428164003Sstefanf				} else
1429164003Sstefanf					subtype = p - types + VSNORMAL;
143017987Speter				break;
143117987Speter			case '%':
143220425Ssteve			case '#':
143317987Speter				{
143417987Speter					int cc = c;
143517987Speter					subtype = c == '#' ? VSTRIMLEFT :
143617987Speter							     VSTRIMRIGHT;
143717987Speter					c = pgetc();
143817987Speter					if (c == cc)
143917987Speter						subtype++;
144017987Speter					else
144117987Speter						pungetc();
144217987Speter					break;
144317987Speter				}
14441556Srgrimes			}
1445164003Sstefanf		} else if (subtype != VSERROR) {
14461556Srgrimes			pungetc();
14471556Srgrimes		}
1448164003Sstefanf		STPUTC('=', out);
144957225Scracauer		if (subtype != VSLENGTH && (dblquote || arinest))
14501556Srgrimes			flags |= VSQUOTE;
14511556Srgrimes		*(stackblock() + typeloc) = subtype | flags;
14521556Srgrimes		if (subtype != VSNORMAL)
14531556Srgrimes			varnest++;
14541556Srgrimes	}
14551556Srgrimes	goto parsesub_return;
14561556Srgrimes}
14571556Srgrimes
14581556Srgrimes
14591556Srgrimes/*
14601556Srgrimes * Parse an arithmetic expansion (indicate start of one and set state)
14611556Srgrimes */
14621556Srgrimesparsearith: {
14631556Srgrimes
14641556Srgrimes	if (++arinest == 1) {
14651556Srgrimes		prevsyntax = syntax;
14661556Srgrimes		syntax = ARISYNTAX;
14671556Srgrimes		USTPUTC(CTLARI, out);
146838887Stegge		if (dblquote)
146938887Stegge			USTPUTC('"',out);
147038887Stegge		else
147138887Stegge			USTPUTC(' ',out);
14721556Srgrimes	} else {
14731556Srgrimes		/*
14741556Srgrimes		 * we collapse embedded arithmetic expansion to
14751556Srgrimes		 * parenthesis, which should be equivalent
14761556Srgrimes		 */
14771556Srgrimes		USTPUTC('(', out);
14781556Srgrimes	}
14791556Srgrimes	goto parsearith_return;
14801556Srgrimes}
14811556Srgrimes
14821556Srgrimes} /* end of readtoken */
14831556Srgrimes
14841556Srgrimes
14851556Srgrimes
14861556Srgrimes#ifdef mkinit
14871556SrgrimesRESET {
14881556Srgrimes	tokpushback = 0;
14891556Srgrimes	checkkwd = 0;
14901556Srgrimes}
14911556Srgrimes#endif
14921556Srgrimes
14931556Srgrimes/*
14941556Srgrimes * Returns true if the text contains nothing to expand (no dollar signs
14951556Srgrimes * or backquotes).
14961556Srgrimes */
14971556Srgrimes
14981556SrgrimesSTATIC int
149990111Simpnoexpand(char *text)
150090111Simp{
150125230Ssteve	char *p;
150225230Ssteve	char c;
15031556Srgrimes
15041556Srgrimes	p = text;
15051556Srgrimes	while ((c = *p++) != '\0') {
150639137Stegge		if ( c == CTLQUOTEMARK)
150739137Stegge			continue;
15081556Srgrimes		if (c == CTLESC)
15091556Srgrimes			p++;
151083675Stegge		else if (BASESYNTAX[(int)c] == CCTL)
15111556Srgrimes			return 0;
15121556Srgrimes	}
15131556Srgrimes	return 1;
15141556Srgrimes}
15151556Srgrimes
15161556Srgrimes
15171556Srgrimes/*
15181556Srgrimes * Return true if the argument is a legal variable name (a letter or
15191556Srgrimes * underscore followed by zero or more letters, underscores, and digits).
15201556Srgrimes */
15211556Srgrimes
15221556Srgrimesint
1523200956Sjillesgoodname(const char *name)
152490111Simp{
1525200956Sjilles	const char *p;
15261556Srgrimes
15271556Srgrimes	p = name;
15281556Srgrimes	if (! is_name(*p))
15291556Srgrimes		return 0;
15301556Srgrimes	while (*++p) {
15311556Srgrimes		if (! is_in_name(*p))
15321556Srgrimes			return 0;
15331556Srgrimes	}
15341556Srgrimes	return 1;
15351556Srgrimes}
15361556Srgrimes
15371556Srgrimes
15381556Srgrimes/*
15391556Srgrimes * Called when an unexpected token is read during the parse.  The argument
15401556Srgrimes * is the token that is expected, or -1 if more than one type of token can
15411556Srgrimes * occur at this point.
15421556Srgrimes */
15431556Srgrimes
15441556SrgrimesSTATIC void
154590111Simpsynexpect(int token)
154617987Speter{
15471556Srgrimes	char msg[64];
15481556Srgrimes
15491556Srgrimes	if (token >= 0) {
15501556Srgrimes		fmtstr(msg, 64, "%s unexpected (expecting %s)",
15511556Srgrimes			tokname[lasttoken], tokname[token]);
15521556Srgrimes	} else {
15531556Srgrimes		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
15541556Srgrimes	}
15551556Srgrimes	synerror(msg);
15561556Srgrimes}
15571556Srgrimes
15581556Srgrimes
15591556SrgrimesSTATIC void
1560201053Sjillessynerror(const char *msg)
156190111Simp{
15621556Srgrimes	if (commandname)
1563201366Sjilles		outfmt(out2, "%s: %d: ", commandname, startlinno);
1564201366Sjilles	outfmt(out2, "Syntax error: %s\n", msg);
15651556Srgrimes	error((char *)NULL);
15661556Srgrimes}
15671556Srgrimes
15681556SrgrimesSTATIC void
156990111Simpsetprompt(int which)
157090111Simp{
15711556Srgrimes	whichprompt = which;
15721556Srgrimes
157317987Speter#ifndef NO_HISTORY
15741556Srgrimes	if (!el)
157517987Speter#endif
1576199629Sjilles	{
15771556Srgrimes		out2str(getprompt(NULL));
1578199629Sjilles		flushout(out2);
1579199629Sjilles	}
15801556Srgrimes}
15811556Srgrimes
15821556Srgrimes/*
15831556Srgrimes * called by editline -- any expansions to the prompt
15841556Srgrimes *    should be added here.
15851556Srgrimes */
15861556Srgrimeschar *
158790111Simpgetprompt(void *unused __unused)
158825905Ssteve{
1589142845Sobrien	static char ps[PROMPTLEN];
1590142845Sobrien	char *fmt;
1591142845Sobrien	int i, j, trim;
1592201053Sjilles	static char internal_error[] = "<internal prompt error>";
1593142845Sobrien
1594142845Sobrien	/*
1595142845Sobrien	 * Select prompt format.
1596142845Sobrien	 */
15971556Srgrimes	switch (whichprompt) {
15981556Srgrimes	case 0:
1599201053Sjilles		fmt = nullstr;
1600142845Sobrien		break;
16011556Srgrimes	case 1:
1602142845Sobrien		fmt = ps1val();
1603142845Sobrien		break;
16041556Srgrimes	case 2:
1605142845Sobrien		fmt = ps2val();
1606142845Sobrien		break;
16071556Srgrimes	default:
1608201053Sjilles		return internal_error;
16091556Srgrimes	}
1610142845Sobrien
1611142845Sobrien	/*
1612142845Sobrien	 * Format prompt string.
1613142845Sobrien	 */
1614142845Sobrien	for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1615142845Sobrien		if (*fmt == '\\')
1616142845Sobrien			switch (*++fmt) {
1617142845Sobrien
1618142845Sobrien				/*
1619142845Sobrien				 * Hostname.
1620142845Sobrien				 *
1621142845Sobrien				 * \h specifies just the local hostname,
1622142845Sobrien				 * \H specifies fully-qualified hostname.
1623142845Sobrien				 */
1624142845Sobrien			case 'h':
1625142845Sobrien			case 'H':
1626149024Sstefanf				ps[i] = '\0';
1627142845Sobrien				gethostname(&ps[i], PROMPTLEN - i);
1628142845Sobrien				/* Skip to end of hostname. */
1629142845Sobrien				trim = (*fmt == 'h') ? '.' : '\0';
1630142845Sobrien				while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1631142845Sobrien					i++;
1632142845Sobrien				break;
1633142845Sobrien
1634142845Sobrien				/*
1635142845Sobrien				 * Working directory.
1636142845Sobrien				 *
1637142845Sobrien				 * \W specifies just the final component,
1638142845Sobrien				 * \w specifies the entire path.
1639142845Sobrien				 */
1640142845Sobrien			case 'W':
1641142845Sobrien			case 'w':
1642149024Sstefanf				ps[i] = '\0';
1643142845Sobrien				getcwd(&ps[i], PROMPTLEN - i);
1644204276Sjh				if (*fmt == 'W' && ps[i + 1] != '\0') {
1645142845Sobrien					/* Final path component only. */
1646142845Sobrien					trim = 1;
1647142845Sobrien					for (j = i; ps[j] != '\0'; j++)
1648142845Sobrien					  if (ps[j] == '/')
1649142845Sobrien						trim = j + 1;
1650142845Sobrien					memmove(&ps[i], &ps[trim],
1651142845Sobrien					    j - trim + 1);
1652142845Sobrien				}
1653142845Sobrien				/* Skip to end of path. */
1654142845Sobrien				while (ps[i + 1] != '\0')
1655142845Sobrien					i++;
1656142845Sobrien				break;
1657142845Sobrien
1658142845Sobrien				/*
1659142845Sobrien				 * Superuser status.
1660142845Sobrien				 *
1661142845Sobrien				 * '$' for normal users, '#' for root.
1662142845Sobrien				 */
1663142845Sobrien			case '$':
1664142845Sobrien				ps[i] = (geteuid() != 0) ? '$' : '#';
1665142845Sobrien				break;
1666142845Sobrien
1667142845Sobrien				/*
1668142845Sobrien				 * A literal \.
1669142845Sobrien				 */
1670142845Sobrien			case '\\':
1671142845Sobrien				ps[i] = '\\';
1672142845Sobrien				break;
1673142845Sobrien
1674142845Sobrien				/*
1675142845Sobrien				 * Emit unrecognized formats verbatim.
1676142845Sobrien				 */
1677142845Sobrien			default:
1678142845Sobrien				ps[i++] = '\\';
1679142845Sobrien				ps[i] = *fmt;
1680142845Sobrien				break;
1681142845Sobrien			}
1682142845Sobrien		else
1683142845Sobrien			ps[i] = *fmt;
1684142845Sobrien	ps[i] = '\0';
1685142845Sobrien	return (ps);
16861556Srgrimes}
1687