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