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