Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.20
      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.20 1994/08/24 05:48:28 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 TEOF:
    463 	case TWORD:
    464 	case TRP:
    465 		tokpushback++;
    466 		return simplecmd(rpp, redir);
    467 	default:
    468 		synexpect(-1);
    469 	}
    470 
    471 	/* Now check for redirection which may follow command */
    472 	while (readtoken() == TREDIR) {
    473 		*rpp = n2 = redirnode;
    474 		rpp = &n2->nfile.next;
    475 		parsefname();
    476 	}
    477 	tokpushback++;
    478 	*rpp = NULL;
    479 	if (redir) {
    480 		if (n1->type != NSUBSHELL) {
    481 			n2 = (union node *)stalloc(sizeof (struct nredir));
    482 			n2->type = NREDIR;
    483 			n2->nredir.n = n1;
    484 			n1 = n2;
    485 		}
    486 		n1->nredir.redirect = redir;
    487 	}
    488 	return n1;
    489 }
    490 
    491 
    492 STATIC union node *
    493 simplecmd(rpp, redir)
    494 	union node **rpp, *redir;
    495 	{
    496 	union node *args, **app;
    497 	union node **orig_rpp = rpp;
    498 	union node *n;
    499 
    500 	/* If we don't have any redirections already, then we must reset */
    501 	/* rpp to be the address of the local redir variable.  */
    502 	if (redir == 0)
    503 		rpp = &redir;
    504 
    505 	args = NULL;
    506 	app = &args;
    507 	/*
    508 	 * We save the incoming value, because we need this for shell
    509 	 * functions.  There can not be a redirect or an argument between
    510 	 * the function name and the open parenthesis.
    511 	 */
    512 	orig_rpp = rpp;
    513 
    514 	for (;;) {
    515 		if (readtoken() == TWORD) {
    516 			n = (union node *)stalloc(sizeof (struct narg));
    517 			n->type = NARG;
    518 			n->narg.text = wordtext;
    519 			n->narg.backquote = backquotelist;
    520 			*app = n;
    521 			app = &n->narg.next;
    522 		} else if (lasttoken == TREDIR) {
    523 			*rpp = n = redirnode;
    524 			rpp = &n->nfile.next;
    525 			parsefname();	/* read name of redirection file */
    526 		} else if (lasttoken == TLP && app == &args->narg.next
    527 					    && rpp == orig_rpp) {
    528 			/* We have a function */
    529 			if (readtoken() != TRP)
    530 				synexpect(TRP);
    531 #ifdef notdef
    532 			if (! goodname(n->narg.text))
    533 				synerror("Bad function name");
    534 #endif
    535 			n->type = NDEFUN;
    536 			n->narg.next = command();
    537 			return n;
    538 		} else {
    539 			tokpushback++;
    540 			break;
    541 		}
    542 	}
    543 	*app = NULL;
    544 	*rpp = NULL;
    545 	n = (union node *)stalloc(sizeof (struct ncmd));
    546 	n->type = NCMD;
    547 	n->ncmd.backgnd = 0;
    548 	n->ncmd.args = args;
    549 	n->ncmd.redirect = redir;
    550 	return n;
    551 }
    552 
    553 STATIC union node *
    554 makename() {
    555 	union node *n;
    556 
    557 	n = (union node *)stalloc(sizeof (struct narg));
    558 	n->type = NARG;
    559 	n->narg.next = NULL;
    560 	n->narg.text = wordtext;
    561 	n->narg.backquote = backquotelist;
    562 	return n;
    563 }
    564 
    565 void fixredir(n, text, err)
    566 	union node *n;
    567 	const char *text;
    568 	int err;
    569 	{
    570 	TRACE(("Fix redir %s %d\n", text, err));
    571 	if (!err)
    572 		n->ndup.vname = NULL;
    573 
    574 	if (is_digit(text[0]) && text[1] == '\0')
    575 		n->ndup.dupfd = digit_val(text[0]);
    576 	else if (text[0] == '-' && text[1] == '\0')
    577 		n->ndup.dupfd = -1;
    578 	else {
    579 
    580 		if (err)
    581 			synerror("Bad fd number");
    582 		else
    583 			n->ndup.vname = makename();
    584 	}
    585 }
    586 
    587 
    588 STATIC void
    589 parsefname() {
    590 	union node *n = redirnode;
    591 
    592 	if (readtoken() != TWORD)
    593 		synexpect(-1);
    594 	if (n->type == NHERE) {
    595 		struct heredoc *here = heredoc;
    596 		struct heredoc *p;
    597 		int i;
    598 
    599 		if (quoteflag == 0)
    600 			n->type = NXHERE;
    601 		TRACE(("Here document %d\n", n->type));
    602 		if (here->striptabs) {
    603 			while (*wordtext == '\t')
    604 				wordtext++;
    605 		}
    606 		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
    607 			synerror("Illegal eof marker for << redirection");
    608 		rmescapes(wordtext);
    609 		here->eofmark = wordtext;
    610 		here->next = NULL;
    611 		if (heredoclist == NULL)
    612 			heredoclist = here;
    613 		else {
    614 			for (p = heredoclist ; p->next ; p = p->next);
    615 			p->next = here;
    616 		}
    617 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    618 		fixredir(n, wordtext, 0);
    619 	} else {
    620 		n->nfile.fname = makename();
    621 	}
    622 }
    623 
    624 
    625 /*
    626  * Input any here documents.
    627  */
    628 
    629 STATIC void
    630 parseheredoc() {
    631 	struct heredoc *here;
    632 	union node *n;
    633 
    634 	while (heredoclist) {
    635 		here = heredoclist;
    636 		heredoclist = here->next;
    637 		if (needprompt) {
    638 			setprompt(2);
    639 			needprompt = 0;
    640 		}
    641 		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
    642 				here->eofmark, here->striptabs);
    643 		n = (union node *)stalloc(sizeof (struct narg));
    644 		n->narg.type = NARG;
    645 		n->narg.next = NULL;
    646 		n->narg.text = wordtext;
    647 		n->narg.backquote = backquotelist;
    648 		here->here->nhere.doc = n;
    649 	}
    650 }
    651 
    652 STATIC int
    653 peektoken() {
    654 	int t;
    655 
    656 	t = readtoken();
    657 	tokpushback++;
    658 	return (t);
    659 }
    660 
    661 STATIC int xxreadtoken();
    662 
    663 STATIC int
    664 readtoken() {
    665 	int t;
    666 	int savecheckkwd = checkkwd;
    667 	struct alias *ap;
    668 #ifdef DEBUG
    669 	int alreadyseen = tokpushback;
    670 #endif
    671 
    672 	top:
    673 	t = xxreadtoken();
    674 
    675 	if (checkkwd) {
    676 		/*
    677 		 * eat newlines
    678 		 */
    679 		if (checkkwd == 2) {
    680 			checkkwd = 0;
    681 			while (t == TNL) {
    682 				parseheredoc();
    683 				t = xxreadtoken();
    684 			}
    685 		} else
    686 			checkkwd = 0;
    687 		/*
    688 		 * check for keywords and aliases
    689 		 */
    690 		if (t == TWORD && !quoteflag) {
    691 			register char * const *pp, *s;
    692 
    693 			for (pp = (char **)parsekwd; *pp; pp++) {
    694 				if (**pp == *wordtext && equal(*pp, wordtext)) {
    695 					lasttoken = t = pp - parsekwd + KWDOFFSET;
    696 					TRACE(("keyword %s recognized\n", tokname[t]));
    697 					goto out;
    698 				}
    699 			}
    700 			if (ap = lookupalias(wordtext, 1)) {
    701 				pushstring(ap->val, strlen(ap->val), ap);
    702 				checkkwd = savecheckkwd;
    703 				goto top;
    704 			}
    705 		}
    706 out:
    707 		checkkwd = 0;
    708 	}
    709 #ifdef DEBUG
    710 	if (!alreadyseen)
    711 	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    712 	else
    713 	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    714 #endif
    715 	return (t);
    716 }
    717 
    718 
    719 /*
    720  * Read the next input token.
    721  * If the token is a word, we set backquotelist to the list of cmds in
    722  *	backquotes.  We set quoteflag to true if any part of the word was
    723  *	quoted.
    724  * If the token is TREDIR, then we set redirnode to a structure containing
    725  *	the redirection.
    726  * In all cases, the variable startlinno is set to the number of the line
    727  *	on which the token starts.
    728  *
    729  * [Change comment:  here documents and internal procedures]
    730  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    731  *  word parsing code into a separate routine.  In this case, readtoken
    732  *  doesn't need to have any internal procedures, but parseword does.
    733  *  We could also make parseoperator in essence the main routine, and
    734  *  have parseword (readtoken1?) handle both words and redirection.]
    735  */
    736 
    737 #define RETURN(token)	return lasttoken = token
    738 
    739 STATIC int
    740 xxreadtoken() {
    741 	register c;
    742 
    743 	if (tokpushback) {
    744 		tokpushback = 0;
    745 		return lasttoken;
    746 	}
    747 	if (needprompt) {
    748 		setprompt(2);
    749 		needprompt = 0;
    750 	}
    751 	startlinno = plinno;
    752 	for (;;) {	/* until token or start of word found */
    753 		c = pgetc_macro();
    754 		if (c == ' ' || c == '\t')
    755 			continue;		/* quick check for white space first */
    756 		switch (c) {
    757 		case ' ': case '\t':
    758 			continue;
    759 		case '#':
    760 			while ((c = pgetc()) != '\n' && c != PEOF);
    761 			pungetc();
    762 			continue;
    763 		case '\\':
    764 			if (pgetc() == '\n') {
    765 				startlinno = ++plinno;
    766 				if (doprompt)
    767 					setprompt(2);
    768 				else
    769 					setprompt(0);
    770 				continue;
    771 			}
    772 			pungetc();
    773 			goto breakloop;
    774 		case '\n':
    775 			plinno++;
    776 			needprompt = doprompt;
    777 			RETURN(TNL);
    778 		case PEOF:
    779 			RETURN(TEOF);
    780 		case '&':
    781 			if (pgetc() == '&')
    782 				RETURN(TAND);
    783 			pungetc();
    784 			RETURN(TBACKGND);
    785 		case '|':
    786 			if (pgetc() == '|')
    787 				RETURN(TOR);
    788 			pungetc();
    789 			RETURN(TPIPE);
    790 		case ';':
    791 			if (pgetc() == ';')
    792 				RETURN(TENDCASE);
    793 			pungetc();
    794 			RETURN(TSEMI);
    795 		case '(':
    796 			RETURN(TLP);
    797 		case ')':
    798 			RETURN(TRP);
    799 		default:
    800 			goto breakloop;
    801 		}
    802 	}
    803 breakloop:
    804 	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
    805 #undef RETURN
    806 }
    807 
    808 
    809 
    810 /*
    811  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
    812  * is not NULL, read a here document.  In the latter case, eofmark is the
    813  * word which marks the end of the document and striptabs is true if
    814  * leading tabs should be stripped from the document.  The argument firstc
    815  * is the first character of the input token or document.
    816  *
    817  * Because C does not have internal subroutines, I have simulated them
    818  * using goto's to implement the subroutine linkage.  The following macros
    819  * will run code that appears at the end of readtoken1.
    820  */
    821 
    822 #define CHECKEND()	{goto checkend; checkend_return:;}
    823 #define PARSEREDIR()	{goto parseredir; parseredir_return:;}
    824 #define PARSESUB()	{goto parsesub; parsesub_return:;}
    825 #define PARSEBACKQOLD()	{oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
    826 #define PARSEBACKQNEW()	{oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
    827 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
    828 
    829 STATIC int
    830 readtoken1(firstc, syntax, eofmark, striptabs)
    831 	int firstc;
    832 	char const *syntax;
    833 	char *eofmark;
    834 	int striptabs;
    835 	{
    836 	register c = firstc;
    837 	register char *out;
    838 	int len;
    839 	char line[EOFMARKLEN + 1];
    840 	struct nodelist *bqlist;
    841 	int quotef;
    842 	int dblquote;
    843 	int varnest;	/* levels of variables expansion */
    844 	int arinest;	/* levels of arithmetic expansion */
    845 	int parenlevel;	/* levels of parens in arithmetic */
    846 	int oldstyle;
    847 	char const *prevsyntax;	/* syntax before arithmetic */
    848 
    849 	startlinno = plinno;
    850 	dblquote = 0;
    851 	if (syntax == DQSYNTAX)
    852 		dblquote = 1;
    853 	quotef = 0;
    854 	bqlist = NULL;
    855 	varnest = 0;
    856 	arinest = 0;
    857 	parenlevel = 0;
    858 
    859 	STARTSTACKSTR(out);
    860 	loop: {	/* for each line, until end of word */
    861 #if ATTY
    862 		if (c == '\034' && doprompt
    863 		 && attyset() && ! equal(termval(), "emacs")) {
    864 			attyline();
    865 			if (syntax == BASESYNTAX)
    866 				return readtoken();
    867 			c = pgetc();
    868 			goto loop;
    869 		}
    870 #endif
    871 		CHECKEND();	/* set c to PEOF if at end of here document */
    872 		for (;;) {	/* until end of line or end of word */
    873 			CHECKSTRSPACE(3, out);	/* permit 3 calls to USTPUTC */
    874 			switch(syntax[c]) {
    875 			case CNL:	/* '\n' */
    876 				if (syntax == BASESYNTAX)
    877 					goto endword;	/* exit outer loop */
    878 				USTPUTC(c, out);
    879 				plinno++;
    880 				if (doprompt)
    881 					setprompt(2);
    882 				else
    883 					setprompt(0);
    884 				c = pgetc();
    885 				goto loop;		/* continue outer loop */
    886 			case CWORD:
    887 				USTPUTC(c, out);
    888 				break;
    889 			case CCTL:
    890 				if (eofmark == NULL || dblquote)
    891 					USTPUTC(CTLESC, out);
    892 				USTPUTC(c, out);
    893 				break;
    894 			case CBACK:	/* backslash */
    895 				c = pgetc();
    896 				if (c == PEOF) {
    897 					USTPUTC('\\', out);
    898 					pungetc();
    899 				} else if (c == '\n') {
    900 					if (doprompt)
    901 						setprompt(2);
    902 					else
    903 						setprompt(0);
    904 				} else {
    905 					if (dblquote && c != '\\' && c != '`' && c != '$'
    906 							 && (c != '"' || eofmark != NULL))
    907 						USTPUTC('\\', out);
    908 					if (SQSYNTAX[c] == CCTL)
    909 						USTPUTC(CTLESC, out);
    910 					USTPUTC(c, out);
    911 					quotef++;
    912 				}
    913 				break;
    914 			case CSQUOTE:
    915 				syntax = SQSYNTAX;
    916 				break;
    917 			case CDQUOTE:
    918 				syntax = DQSYNTAX;
    919 				dblquote = 1;
    920 				break;
    921 			case CENDQUOTE:
    922 				if (eofmark) {
    923 					USTPUTC(c, out);
    924 				} else {
    925 					if (arinest)
    926 						syntax = ARISYNTAX;
    927 					else
    928 						syntax = BASESYNTAX;
    929 					quotef++;
    930 					dblquote = 0;
    931 				}
    932 				break;
    933 			case CVAR:	/* '$' */
    934 				PARSESUB();		/* parse substitution */
    935 				break;
    936 			case CENDVAR:	/* '}' */
    937 				if (varnest > 0) {
    938 					varnest--;
    939 					USTPUTC(CTLENDVAR, out);
    940 				} else {
    941 					USTPUTC(c, out);
    942 				}
    943 				break;
    944 			case CLP:	/* '(' in arithmetic */
    945 				parenlevel++;
    946 				USTPUTC(c, out);
    947 				break;
    948 			case CRP:	/* ')' in arithmetic */
    949 				if (parenlevel > 0) {
    950 					USTPUTC(c, out);
    951 					--parenlevel;
    952 				} else {
    953 					if (pgetc() == ')') {
    954 						if (--arinest == 0) {
    955 							USTPUTC(CTLENDARI, out);
    956 							syntax = prevsyntax;
    957 						} else
    958 							USTPUTC(')', out);
    959 					} else {
    960 						/*
    961 						 * unbalanced parens
    962 						 *  (don't 2nd guess - no error)
    963 						 */
    964 						pungetc();
    965 						USTPUTC(')', out);
    966 					}
    967 				}
    968 				break;
    969 			case CBQUOTE:	/* '`' */
    970 				PARSEBACKQOLD();
    971 				break;
    972 			case CEOF:
    973 				goto endword;		/* exit outer loop */
    974 			default:
    975 				if (varnest == 0)
    976 					goto endword;	/* exit outer loop */
    977 				USTPUTC(c, out);
    978 			}
    979 			c = pgetc_macro();
    980 		}
    981 	}
    982 endword:
    983 	if (syntax == ARISYNTAX)
    984 		synerror("Missing '))'");
    985 	if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
    986 		synerror("Unterminated quoted string");
    987 	if (varnest != 0) {
    988 		startlinno = plinno;
    989 		synerror("Missing '}'");
    990 	}
    991 	USTPUTC('\0', out);
    992 	len = out - stackblock();
    993 	out = stackblock();
    994 	if (eofmark == NULL) {
    995 		if ((c == '>' || c == '<')
    996 		 && quotef == 0
    997 		 && len <= 2
    998 		 && (*out == '\0' || is_digit(*out))) {
    999 			PARSEREDIR();
   1000 			return lasttoken = TREDIR;
   1001 		} else {
   1002 			pungetc();
   1003 		}
   1004 	}
   1005 	quoteflag = quotef;
   1006 	backquotelist = bqlist;
   1007 	grabstackblock(len);
   1008 	wordtext = out;
   1009 	return lasttoken = TWORD;
   1010 /* end of readtoken routine */
   1011 
   1012 
   1013 
   1014 /*
   1015  * Check to see whether we are at the end of the here document.  When this
   1016  * is called, c is set to the first character of the next input line.  If
   1017  * we are at the end of the here document, this routine sets the c to PEOF.
   1018  */
   1019 
   1020 checkend: {
   1021 	if (eofmark) {
   1022 		if (striptabs) {
   1023 			while (c == '\t')
   1024 				c = pgetc();
   1025 		}
   1026 		if (c == *eofmark) {
   1027 			if (pfgets(line, sizeof line) != NULL) {
   1028 				register char *p, *q;
   1029 
   1030 				p = line;
   1031 				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
   1032 				if (*p == '\n' && *q == '\0') {
   1033 					c = PEOF;
   1034 					plinno++;
   1035 					needprompt = doprompt;
   1036 				} else {
   1037 					pushstring(line, strlen(line), NULL);
   1038 				}
   1039 			}
   1040 		}
   1041 	}
   1042 	goto checkend_return;
   1043 }
   1044 
   1045 
   1046 /*
   1047  * Parse a redirection operator.  The variable "out" points to a string
   1048  * specifying the fd to be redirected.  The variable "c" contains the
   1049  * first character of the redirection operator.
   1050  */
   1051 
   1052 parseredir: {
   1053 	char fd = *out;
   1054 	union node *np;
   1055 
   1056 	np = (union node *)stalloc(sizeof (struct nfile));
   1057 	if (c == '>') {
   1058 		np->nfile.fd = 1;
   1059 		c = pgetc();
   1060 		if (c == '>')
   1061 			np->type = NAPPEND;
   1062 		else if (c == '&')
   1063 			np->type = NTOFD;
   1064 		else {
   1065 			np->type = NTO;
   1066 			pungetc();
   1067 		}
   1068 	} else {	/* c == '<' */
   1069 		np->nfile.fd = 0;
   1070 		c = pgetc();
   1071 		if (c == '<') {
   1072 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1073 				np = (union node *)stalloc(sizeof (struct nhere));
   1074 				np->nfile.fd = 0;
   1075 			}
   1076 			np->type = NHERE;
   1077 			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
   1078 			heredoc->here = np;
   1079 			if ((c = pgetc()) == '-') {
   1080 				heredoc->striptabs = 1;
   1081 			} else {
   1082 				heredoc->striptabs = 0;
   1083 				pungetc();
   1084 			}
   1085 		} else if (c == '&')
   1086 			np->type = NFROMFD;
   1087 		else {
   1088 			np->type = NFROM;
   1089 			pungetc();
   1090 		}
   1091 	}
   1092 	if (fd != '\0')
   1093 		np->nfile.fd = digit_val(fd);
   1094 	redirnode = np;
   1095 	goto parseredir_return;
   1096 }
   1097 
   1098 
   1099 /*
   1100  * Parse a substitution.  At this point, we have read the dollar sign
   1101  * and nothing else.
   1102  */
   1103 
   1104 parsesub: {
   1105 	int subtype;
   1106 	int typeloc;
   1107 	int flags;
   1108 	char *p;
   1109 #ifndef GDB_HACK
   1110 	static const char types[] = "}-+?=";
   1111 #endif
   1112 
   1113 	c = pgetc();
   1114 	if (c != '(' && c != '{' && !is_name(c) && !is_special(c)) {
   1115 		USTPUTC('$', out);
   1116 		pungetc();
   1117 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1118 		if (pgetc() == '(') {
   1119 			PARSEARITH();
   1120 		} else {
   1121 			pungetc();
   1122 			PARSEBACKQNEW();
   1123 		}
   1124 	} else {
   1125 		USTPUTC(CTLVAR, out);
   1126 		typeloc = out - stackblock();
   1127 		USTPUTC(VSNORMAL, out);
   1128 		subtype = VSNORMAL;
   1129 		if (c == '{') {
   1130 			c = pgetc();
   1131 			subtype = 0;
   1132 		}
   1133 		if (is_name(c)) {
   1134 			do {
   1135 				STPUTC(c, out);
   1136 				c = pgetc();
   1137 			} while (is_in_name(c));
   1138 		} else {
   1139 			if (! is_special(c))
   1140 badsub:				synerror("Bad substitution");
   1141 			USTPUTC(c, out);
   1142 			c = pgetc();
   1143 		}
   1144 		STPUTC('=', out);
   1145 		flags = 0;
   1146 		if (subtype == 0) {
   1147 			if (c == ':') {
   1148 				flags = VSNUL;
   1149 				c = pgetc();
   1150 			}
   1151 			p = strchr(types, c);
   1152 			if (p == NULL)
   1153 				goto badsub;
   1154 			subtype = p - types + VSNORMAL;
   1155 		} else {
   1156 			pungetc();
   1157 		}
   1158 		if (dblquote || arinest)
   1159 			flags |= VSQUOTE;
   1160 		*(stackblock() + typeloc) = subtype | flags;
   1161 		if (subtype != VSNORMAL)
   1162 			varnest++;
   1163 	}
   1164 	goto parsesub_return;
   1165 }
   1166 
   1167 
   1168 /*
   1169  * Called to parse command substitutions.  Newstyle is set if the command
   1170  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
   1171  * list of commands (passed by reference), and savelen is the number of
   1172  * characters on the top of the stack which must be preserved.
   1173  */
   1174 
   1175 parsebackq: {
   1176 	struct nodelist **nlpp;
   1177 	int savepbq;
   1178 	union node *n;
   1179 	char *volatile str;
   1180 	struct jmploc jmploc;
   1181 	struct jmploc *volatile savehandler;
   1182 	int savelen;
   1183 
   1184 	savepbq = parsebackquote;
   1185 	if (setjmp(jmploc.loc)) {
   1186 		if (str)
   1187 			ckfree(str);
   1188 		parsebackquote = 0;
   1189 		handler = savehandler;
   1190 		longjmp(handler->loc, 1);
   1191 	}
   1192 	INTOFF;
   1193 	str = NULL;
   1194 	savelen = out - stackblock();
   1195 	if (savelen > 0) {
   1196 		str = ckmalloc(savelen);
   1197 		bcopy(stackblock(), str, savelen);
   1198 	}
   1199 	savehandler = handler;
   1200 	handler = &jmploc;
   1201 	INTON;
   1202         if (oldstyle) {
   1203                 /* We must read until the closing backquote, giving special
   1204                    treatment to some slashes, and then push the string and
   1205                    reread it as input, interpreting it normally.  */
   1206                 register char *out;
   1207                 register c;
   1208                 int savelen;
   1209                 char *str;
   1210 
   1211                 STARTSTACKSTR(out);
   1212                 while ((c = pgetc ()) != '`') {
   1213                        if (c == '\\') {
   1214                                 c = pgetc ();
   1215                                 if (c != '\\' && c != '`' && c != '$'
   1216                                     && (!dblquote || c != '"'))
   1217                                         STPUTC('\\', out);
   1218                        }
   1219                        STPUTC(c, out);
   1220                 }
   1221                 STPUTC('\0', out);
   1222                 savelen = out - stackblock();
   1223                 if (savelen > 0) {
   1224                         str = ckmalloc(savelen);
   1225                         bcopy(stackblock(), str, savelen);
   1226                 }
   1227                 setinputstring(str, 1);
   1228         }
   1229 	nlpp = &bqlist;
   1230 	while (*nlpp)
   1231 		nlpp = &(*nlpp)->next;
   1232 	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
   1233 	(*nlpp)->next = NULL;
   1234 	parsebackquote = oldstyle;
   1235 	n = list(0);
   1236         if (!oldstyle && (readtoken() != TRP))
   1237                 synexpect(TRP);
   1238 	(*nlpp)->n = n;
   1239         /* Start reading from old file again.  */
   1240         if (oldstyle)
   1241                 popfile();
   1242 	while (stackblocksize() <= savelen)
   1243 		growstackblock();
   1244 	STARTSTACKSTR(out);
   1245 	if (str) {
   1246 		bcopy(str, out, savelen);
   1247 		STADJUST(savelen, out);
   1248 		INTOFF;
   1249 		ckfree(str);
   1250 		str = NULL;
   1251 		INTON;
   1252 	}
   1253 	parsebackquote = savepbq;
   1254 	handler = savehandler;
   1255 	if (arinest || dblquote)
   1256 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1257 	else
   1258 		USTPUTC(CTLBACKQ, out);
   1259 	if (oldstyle)
   1260 		goto parsebackq_oldreturn;
   1261 	else
   1262 		goto parsebackq_newreturn;
   1263 }
   1264 
   1265 /*
   1266  * Parse an arithmetic expansion (indicate start of one and set state)
   1267  */
   1268 parsearith: {
   1269 
   1270 	if (++arinest == 1) {
   1271 		prevsyntax = syntax;
   1272 		syntax = ARISYNTAX;
   1273 		USTPUTC(CTLARI, out);
   1274 	} else {
   1275 		/*
   1276 		 * we collapse embedded arithmetic expansion to
   1277 		 * parenthesis, which should be equivalent
   1278 		 */
   1279 		USTPUTC('(', out);
   1280 	}
   1281 	goto parsearith_return;
   1282 }
   1283 
   1284 } /* end of readtoken */
   1285 
   1286 
   1287 
   1288 #ifdef mkinit
   1289 RESET {
   1290 	tokpushback = 0;
   1291 	checkkwd = 0;
   1292 }
   1293 #endif
   1294 
   1295 /*
   1296  * Returns true if the text contains nothing to expand (no dollar signs
   1297  * or backquotes).
   1298  */
   1299 
   1300 STATIC int
   1301 noexpand(text)
   1302 	char *text;
   1303 	{
   1304 	register char *p;
   1305 	register char c;
   1306 
   1307 	p = text;
   1308 	while ((c = *p++) != '\0') {
   1309 		if (c == CTLESC)
   1310 			p++;
   1311 		else if (BASESYNTAX[c] == CCTL)
   1312 			return 0;
   1313 	}
   1314 	return 1;
   1315 }
   1316 
   1317 
   1318 /*
   1319  * Return true if the argument is a legal variable name (a letter or
   1320  * underscore followed by zero or more letters, underscores, and digits).
   1321  */
   1322 
   1323 int
   1324 goodname(name)
   1325 	char *name;
   1326 	{
   1327 	register char *p;
   1328 
   1329 	p = name;
   1330 	if (! is_name(*p))
   1331 		return 0;
   1332 	while (*++p) {
   1333 		if (! is_in_name(*p))
   1334 			return 0;
   1335 	}
   1336 	return 1;
   1337 }
   1338 
   1339 
   1340 /*
   1341  * Called when an unexpected token is read during the parse.  The argument
   1342  * is the token that is expected, or -1 if more than one type of token can
   1343  * occur at this point.
   1344  */
   1345 
   1346 STATIC void
   1347 synexpect(token) {
   1348 	char msg[64];
   1349 
   1350 	if (token >= 0) {
   1351 		fmtstr(msg, 64, "%s unexpected (expecting %s)",
   1352 			tokname[lasttoken], tokname[token]);
   1353 	} else {
   1354 		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
   1355 	}
   1356 	synerror(msg);
   1357 }
   1358 
   1359 
   1360 STATIC void
   1361 synerror(msg)
   1362 	char *msg;
   1363 	{
   1364 	if (commandname)
   1365 		outfmt(&errout, "%s: %d: ", commandname, startlinno);
   1366 	outfmt(&errout, "Syntax error: %s\n", msg);
   1367 	error((char *)NULL);
   1368 }
   1369 
   1370 STATIC void
   1371 setprompt(which)
   1372 	int which;
   1373 	{
   1374 	whichprompt = which;
   1375 
   1376 #ifndef NO_HISTORY
   1377 	if (!el)
   1378 #endif
   1379 		out2str(getprompt(NULL));
   1380 }
   1381 
   1382 /*
   1383  * called by editline -- any expansions to the prompt
   1384  *    should be added here.
   1385  */
   1386 char *
   1387 getprompt(unused)
   1388 	void *unused;
   1389 	{
   1390 	switch (whichprompt) {
   1391 	case 0:
   1392 		return "";
   1393 	case 1:
   1394 		return ps1val();
   1395 	case 2:
   1396 		return ps2val();
   1397 	default:
   1398 		return "<internal prompt error>";
   1399 	}
   1400 }
   1401