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