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