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