Home | History | Annotate | Line # | Download | only in sh
parser.c revision 1.115
      1 /*	$NetBSD: parser.c,v 1.115 2016/03/31 23:11:05 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.115 2016/03/31 23:11:05 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 /* 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 int funclinno;			/* line # where the current function started */
    103 
    104 
    105 STATIC union node *list(int, int);
    106 STATIC union node *andor(void);
    107 STATIC union node *pipeline(void);
    108 STATIC union node *command(void);
    109 STATIC union node *simplecmd(union node **, union node *);
    110 STATIC union node *makename(void);
    111 STATIC void parsefname(void);
    112 STATIC void slurp_heredoc(char *const, const int, const int);
    113 STATIC void readheredocs(void);
    114 STATIC int peektoken(void);
    115 STATIC int readtoken(void);
    116 STATIC int xxreadtoken(void);
    117 STATIC int readtoken1(int, char const *, int);
    118 STATIC int noexpand(char *);
    119 STATIC void synexpect(int, const char *) __dead;
    120 STATIC void synerror(const char *) __dead;
    121 STATIC void setprompt(int);
    122 
    123 
    124 static const char EOFhere[] = "EOF reading here (<<) document";
    125 
    126 
    127 /*
    128  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
    129  * valid parse tree indicating a blank line.)
    130  */
    131 
    132 union node *
    133 parsecmd(int interact)
    134 {
    135 	int t;
    136 
    137 	tokpushback = 0;
    138 	doprompt = interact;
    139 	if (doprompt)
    140 		setprompt(1);
    141 	else
    142 		setprompt(0);
    143 	needprompt = 0;
    144 	t = readtoken();
    145 	if (t == TEOF)
    146 		return NEOF;
    147 	if (t == TNL)
    148 		return NULL;
    149 	tokpushback++;
    150 	return list(1, 0);
    151 }
    152 
    153 
    154 STATIC union node *
    155 list(int nlflag, int erflag)
    156 {
    157 	union node *n1, *n2, *n3;
    158 	int tok;
    159 	TRACE(("list(%d,%d): entered\n", nlflag, erflag));
    160 
    161 	checkkwd = 2;
    162 	if (nlflag == 0 && tokendlist[peektoken()])
    163 		return NULL;
    164 	n1 = NULL;
    165 	for (;;) {
    166 		n2 = andor();
    167 		tok = readtoken();
    168 		if (tok == TBACKGND) {
    169 			if (n2->type == NCMD || n2->type == NPIPE) {
    170 				n2->ncmd.backgnd = 1;
    171 			} else if (n2->type == NREDIR) {
    172 				n2->type = NBACKGND;
    173 			} else {
    174 				n3 = stalloc(sizeof(struct nredir));
    175 				n3->type = NBACKGND;
    176 				n3->nredir.n = n2;
    177 				n3->nredir.redirect = NULL;
    178 				n2 = n3;
    179 			}
    180 		}
    181 		if (n1 == NULL) {
    182 			n1 = n2;
    183 		}
    184 		else {
    185 			n3 = stalloc(sizeof(struct nbinary));
    186 			n3->type = NSEMI;
    187 			n3->nbinary.ch1 = n1;
    188 			n3->nbinary.ch2 = n2;
    189 			n1 = n3;
    190 		}
    191 		switch (tok) {
    192 		case TBACKGND:
    193 		case TSEMI:
    194 			tok = readtoken();
    195 			/* FALLTHROUGH */
    196 		case TNL:
    197 			if (tok == TNL) {
    198 				readheredocs();
    199 				if (nlflag)
    200 					return n1;
    201 			} else {
    202 				tokpushback++;
    203 			}
    204 			checkkwd = 2;
    205 			if (tokendlist[peektoken()])
    206 				return n1;
    207 			break;
    208 		case TEOF:
    209 			if (heredoclist)
    210 				readheredocs();
    211 			else
    212 				pungetc();	/* push back EOF on input */
    213 			return n1;
    214 		default:
    215 			if (nlflag || erflag)
    216 				synexpect(-1, 0);
    217 			tokpushback++;
    218 			return n1;
    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 = 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 STATIC union node *
    250 pipeline(void)
    251 {
    252 	union node *n1, *n2, *pipenode;
    253 	struct nodelist *lp, *prev;
    254 	int negate;
    255 
    256 	TRACE(("pipeline: entered\n"));
    257 
    258 	negate = 0;
    259 	checkkwd = 2;
    260 	while (readtoken() == TNOT) {
    261 		TRACE(("pipeline: TNOT recognized\n"));
    262 		negate = !negate;
    263 	}
    264 	tokpushback++;
    265 	n1 = command();
    266 	if (readtoken() == TPIPE) {
    267 		pipenode = stalloc(sizeof(struct npipe));
    268 		pipenode->type = NPIPE;
    269 		pipenode->npipe.backgnd = 0;
    270 		lp = stalloc(sizeof(struct nodelist));
    271 		pipenode->npipe.cmdlist = lp;
    272 		lp->n = n1;
    273 		do {
    274 			prev = lp;
    275 			lp = stalloc(sizeof(struct nodelist));
    276 			lp->n = command();
    277 			prev->next = lp;
    278 		} while (readtoken() == TPIPE);
    279 		lp->next = NULL;
    280 		n1 = pipenode;
    281 	}
    282 	tokpushback++;
    283 	if (negate) {
    284 		TRACE(("negate pipeline\n"));
    285 		n2 = stalloc(sizeof(struct nnot));
    286 		n2->type = NNOT;
    287 		n2->nnot.com = n1;
    288 		return n2;
    289 	} else
    290 		return n1;
    291 }
    292 
    293 
    294 
    295 STATIC union node *
    296 command(void)
    297 {
    298 	union node *n1, *n2;
    299 	union node *ap, **app;
    300 	union node *cp, **cpp;
    301 	union node *redir, **rpp;
    302 	int t, negate = 0;
    303 
    304 	TRACE(("command: entered\n"));
    305 
    306 	checkkwd = 2;
    307 	redir = NULL;
    308 	n1 = NULL;
    309 	rpp = &redir;
    310 
    311 	/* Check for redirection which may precede command */
    312 	while (readtoken() == TREDIR) {
    313 		*rpp = n2 = redirnode;
    314 		rpp = &n2->nfile.next;
    315 		parsefname();
    316 	}
    317 	tokpushback++;
    318 
    319 	while (readtoken() == TNOT) {
    320 		TRACE(("command: TNOT recognized\n"));
    321 		negate = !negate;
    322 	}
    323 	tokpushback++;
    324 
    325 	switch (readtoken()) {
    326 	case TIF:
    327 		n1 = stalloc(sizeof(struct nif));
    328 		n1->type = NIF;
    329 		n1->nif.test = list(0, 0);
    330 		if (readtoken() != TTHEN)
    331 			synexpect(TTHEN, 0);
    332 		n1->nif.ifpart = list(0, 0);
    333 		n2 = n1;
    334 		while (readtoken() == TELIF) {
    335 			n2->nif.elsepart = stalloc(sizeof(struct nif));
    336 			n2 = n2->nif.elsepart;
    337 			n2->type = NIF;
    338 			n2->nif.test = list(0, 0);
    339 			if (readtoken() != TTHEN)
    340 				synexpect(TTHEN, 0);
    341 			n2->nif.ifpart = list(0, 0);
    342 		}
    343 		if (lasttoken == TELSE)
    344 			n2->nif.elsepart = list(0, 0);
    345 		else {
    346 			n2->nif.elsepart = NULL;
    347 			tokpushback++;
    348 		}
    349 		if (readtoken() != TFI)
    350 			synexpect(TFI, 0);
    351 		checkkwd = 1;
    352 		break;
    353 	case TWHILE:
    354 	case TUNTIL: {
    355 		int got;
    356 		n1 = stalloc(sizeof(struct nbinary));
    357 		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
    358 		n1->nbinary.ch1 = list(0, 0);
    359 		if ((got=readtoken()) != TDO) {
    360 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
    361 			synexpect(TDO, 0);
    362 		}
    363 		n1->nbinary.ch2 = list(0, 0);
    364 		if (readtoken() != TDONE)
    365 			synexpect(TDONE, 0);
    366 		checkkwd = 1;
    367 		break;
    368 	}
    369 	case TFOR:
    370 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
    371 			synerror("Bad for loop variable");
    372 		n1 = stalloc(sizeof(struct nfor));
    373 		n1->type = NFOR;
    374 		n1->nfor.var = wordtext;
    375 		if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
    376 			app = &ap;
    377 			while (readtoken() == TWORD) {
    378 				n2 = stalloc(sizeof(struct narg));
    379 				n2->type = NARG;
    380 				n2->narg.text = wordtext;
    381 				n2->narg.backquote = backquotelist;
    382 				*app = n2;
    383 				app = &n2->narg.next;
    384 			}
    385 			*app = NULL;
    386 			n1->nfor.args = ap;
    387 			if (lasttoken != TNL && lasttoken != TSEMI)
    388 				synexpect(-1, 0);
    389 		} else {
    390 			static char argvars[5] = {
    391 			    CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
    392 			};
    393 			n2 = stalloc(sizeof(struct narg));
    394 			n2->type = NARG;
    395 			n2->narg.text = argvars;
    396 			n2->narg.backquote = NULL;
    397 			n2->narg.next = NULL;
    398 			n1->nfor.args = n2;
    399 			/*
    400 			 * Newline or semicolon here is optional (but note
    401 			 * that the original Bourne shell only allowed NL).
    402 			 */
    403 			if (lasttoken != TNL && lasttoken != TSEMI)
    404 				tokpushback++;
    405 		}
    406 		checkkwd = 2;
    407 		if ((t = readtoken()) == TDO)
    408 			t = TDONE;
    409 		else if (t == TBEGIN)
    410 			t = TEND;
    411 		else
    412 			synexpect(-1, 0);
    413 		n1->nfor.body = list(0, 0);
    414 		if (readtoken() != t)
    415 			synexpect(t, 0);
    416 		checkkwd = 1;
    417 		break;
    418 	case TCASE:
    419 		n1 = stalloc(sizeof(struct ncase));
    420 		n1->type = NCASE;
    421 		if (readtoken() != TWORD)
    422 			synexpect(TWORD, 0);
    423 		n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
    424 		n2->type = NARG;
    425 		n2->narg.text = wordtext;
    426 		n2->narg.backquote = backquotelist;
    427 		n2->narg.next = NULL;
    428 		while (readtoken() == TNL);
    429 		if (lasttoken != TWORD || ! equal(wordtext, "in"))
    430 			synexpect(-1, "in");
    431 		cpp = &n1->ncase.cases;
    432 		noalias = 1;
    433 		checkkwd = 2, readtoken();
    434 		/*
    435 		 * Both ksh and bash accept 'case x in esac'
    436 		 * so configure scripts started taking advantage of this.
    437 		 * The page: http://pubs.opengroup.org/onlinepubs/\
    438 		 * 009695399/utilities/xcu_chap02.html contradicts itself,
    439 		 * as to if this is legal; the "Case Conditional Format"
    440 		 * paragraph shows one case is required, but the "Grammar"
    441 		 * section shows a grammar that explicitly allows the no
    442 		 * case option.
    443 		 */
    444 		while (lasttoken != TESAC) {
    445 			*cpp = cp = stalloc(sizeof(struct nclist));
    446 			if (lasttoken == TLP)
    447 				readtoken();
    448 			cp->type = NCLIST;
    449 			app = &cp->nclist.pattern;
    450 			for (;;) {
    451 				*app = ap = stalloc(sizeof(struct narg));
    452 				ap->type = NARG;
    453 				ap->narg.text = wordtext;
    454 				ap->narg.backquote = backquotelist;
    455 				if (checkkwd = 2, readtoken() != TPIPE)
    456 					break;
    457 				app = &ap->narg.next;
    458 				readtoken();
    459 			}
    460 			ap->narg.next = NULL;
    461 			noalias = 0;
    462 			if (lasttoken != TRP) {
    463 				synexpect(TRP, 0);
    464 			}
    465 			cp->nclist.body = list(0, 0);
    466 
    467 			checkkwd = 2;
    468 			if ((t = readtoken()) != TESAC) {
    469 				if (t != TENDCASE) {
    470 					noalias = 0;
    471 					synexpect(TENDCASE, 0);
    472 				} else {
    473 					noalias = 1;
    474 					checkkwd = 2;
    475 					readtoken();
    476 				}
    477 			}
    478 			cpp = &cp->nclist.next;
    479 		}
    480 		noalias = 0;
    481 		*cpp = NULL;
    482 		checkkwd = 1;
    483 		break;
    484 	case TLP:
    485 		n1 = stalloc(sizeof(struct nredir));
    486 		n1->type = NSUBSHELL;
    487 		n1->nredir.n = list(0, 0);
    488 		n1->nredir.redirect = NULL;
    489 		if (readtoken() != TRP)
    490 			synexpect(TRP, 0);
    491 		checkkwd = 1;
    492 		break;
    493 	case TBEGIN:
    494 		n1 = list(0, 0);
    495 		if (readtoken() != TEND)
    496 			synexpect(TEND, 0);
    497 		checkkwd = 1;
    498 		break;
    499 	/* Handle an empty command like other simple commands.  */
    500 	case TSEMI:
    501 		/*
    502 		 * An empty command before a ; doesn't make much sense, and
    503 		 * should certainly be disallowed in the case of `if ;'.
    504 		 */
    505 		if (!redir)
    506 			synexpect(-1, 0);
    507 	case TAND:
    508 	case TOR:
    509 	case TNL:
    510 	case TEOF:
    511 	case TWORD:
    512 	case TRP:
    513 		tokpushback++;
    514 		n1 = simplecmd(rpp, redir);
    515 		goto checkneg;
    516 	case TENDCASE:
    517 		if (redir) {
    518 			tokpushback++;
    519 			goto checkneg;
    520 		}
    521 		/* FALLTHROUGH */
    522 	default:
    523 		synexpect(-1, 0);
    524 		/* NOTREACHED */
    525 	}
    526 
    527 	/* Now check for redirection which may follow command */
    528 	while (readtoken() == TREDIR) {
    529 		*rpp = n2 = redirnode;
    530 		rpp = &n2->nfile.next;
    531 		parsefname();
    532 	}
    533 	tokpushback++;
    534 	*rpp = NULL;
    535 	if (redir) {
    536 		if (n1->type != NSUBSHELL) {
    537 			n2 = stalloc(sizeof(struct nredir));
    538 			n2->type = NREDIR;
    539 			n2->nredir.n = n1;
    540 			n1 = n2;
    541 		}
    542 		n1->nredir.redirect = redir;
    543 	}
    544 
    545 checkneg:
    546 	if (negate) {
    547 		TRACE(("negate command\n"));
    548 		n2 = stalloc(sizeof(struct nnot));
    549 		n2->type = NNOT;
    550 		n2->nnot.com = n1;
    551 		return n2;
    552 	}
    553 	else
    554 		return n1;
    555 }
    556 
    557 
    558 STATIC union node *
    559 simplecmd(union node **rpp, union node *redir)
    560 {
    561 	union node *args, **app;
    562 	union node *n = NULL, *n2;
    563 	int negate = 0;
    564 
    565 	/* If we don't have any redirections already, then we must reset */
    566 	/* rpp to be the address of the local redir variable.  */
    567 	if (redir == 0)
    568 		rpp = &redir;
    569 
    570 	args = NULL;
    571 	app = &args;
    572 
    573 	while (readtoken() == TNOT) {
    574 		TRACE(("simplcmd: TNOT recognized\n"));
    575 		negate = !negate;
    576 	}
    577 	tokpushback++;
    578 
    579 	for (;;) {
    580 		if (readtoken() == TWORD) {
    581 			n = stalloc(sizeof(struct narg));
    582 			n->type = NARG;
    583 			n->narg.text = wordtext;
    584 			n->narg.backquote = backquotelist;
    585 			*app = n;
    586 			app = &n->narg.next;
    587 		} else if (lasttoken == TREDIR) {
    588 			*rpp = n = redirnode;
    589 			rpp = &n->nfile.next;
    590 			parsefname();	/* read name of redirection file */
    591 		} else if (lasttoken == TLP && app == &args->narg.next
    592 					    && redir == 0) {
    593 			/* We have a function */
    594 			if (readtoken() != TRP)
    595 				synexpect(TRP, 0);
    596 			funclinno = plinno;
    597 			rmescapes(n->narg.text);
    598 			if (!goodname(n->narg.text))
    599 				synerror("Bad function name");
    600 			n->type = NDEFUN;
    601 			n->narg.next = command();
    602 			funclinno = 0;
    603 			goto checkneg;
    604 		} else {
    605 			tokpushback++;
    606 			break;
    607 		}
    608 	}
    609 	*app = NULL;
    610 	*rpp = NULL;
    611 	n = stalloc(sizeof(struct ncmd));
    612 	n->type = NCMD;
    613 	n->ncmd.backgnd = 0;
    614 	n->ncmd.args = args;
    615 	n->ncmd.redirect = redir;
    616 
    617 checkneg:
    618 	if (negate) {
    619 		TRACE(("negate simplecmd\n"));
    620 		n2 = stalloc(sizeof(struct nnot));
    621 		n2->type = NNOT;
    622 		n2->nnot.com = n;
    623 		return n2;
    624 	}
    625 	else
    626 		return n;
    627 }
    628 
    629 STATIC union node *
    630 makename(void)
    631 {
    632 	union node *n;
    633 
    634 	n = stalloc(sizeof(struct narg));
    635 	n->type = NARG;
    636 	n->narg.next = NULL;
    637 	n->narg.text = wordtext;
    638 	n->narg.backquote = backquotelist;
    639 	return n;
    640 }
    641 
    642 void
    643 fixredir(union node *n, const char *text, int err)
    644 {
    645 	TRACE(("Fix redir %s %d\n", text, err));
    646 	if (!err)
    647 		n->ndup.vname = NULL;
    648 
    649 	if (is_number(text))
    650 		n->ndup.dupfd = number(text);
    651 	else if (text[0] == '-' && text[1] == '\0')
    652 		n->ndup.dupfd = -1;
    653 	else {
    654 
    655 		if (err)
    656 			synerror("Bad fd number");
    657 		else
    658 			n->ndup.vname = makename();
    659 	}
    660 }
    661 
    662 
    663 STATIC void
    664 parsefname(void)
    665 {
    666 	union node *n = redirnode;
    667 
    668 	if (readtoken() != TWORD)
    669 		synexpect(-1, 0);
    670 	if (n->type == NHERE) {
    671 		struct heredoc *here = heredoc;
    672 		struct heredoc *p;
    673 
    674 		if (quoteflag == 0)
    675 			n->type = NXHERE;
    676 		TRACE(("Here document %d\n", n->type));
    677 		if (here->striptabs) {
    678 			while (*wordtext == '\t')
    679 				wordtext++;
    680 		}
    681 
    682 		/*
    683 		 * this test is not really necessary, we are not
    684 		 * required to expand wordtext, but there's no reason
    685 		 * it cannot be $$ or something like that - that would
    686 		 * not mean the pid, but literally two '$' characters.
    687 		 * There is no need for limits on what the word can be.
    688 		 * However, it needs to stay literal as entered, not
    689 		 * have $ converted to CTLVAR or something, which as
    690 		 * the parser is, at the minute, is impossible to prevent.
    691 		 * So, leave it like this until the rest of the parser is fixed.
    692 		 */
    693 		if (! noexpand(wordtext))
    694 			synerror("Illegal eof marker for << redirection");
    695 
    696 		rmescapes(wordtext);
    697 		here->eofmark = wordtext;
    698 		here->next = NULL;
    699 		if (heredoclist == NULL)
    700 			heredoclist = here;
    701 		else {
    702 			for (p = heredoclist ; p->next ; p = p->next)
    703 				continue;
    704 			p->next = here;
    705 		}
    706 	} else if (n->type == NTOFD || n->type == NFROMFD) {
    707 		fixredir(n, wordtext, 0);
    708 	} else {
    709 		n->nfile.fname = makename();
    710 	}
    711 }
    712 
    713 /*
    714  * Check to see whether we are at the end of the here document.  When this
    715  * is called, c is set to the first character of the next input line.  If
    716  * we are at the end of the here document, this routine sets the c to PEOF.
    717  * The new value of c is returned.
    718  */
    719 
    720 static int
    721 checkend(int c, char * const eofmark, const int striptabs)
    722 {
    723 	if (striptabs) {
    724 		while (c == '\t')
    725 			c = pgetc();
    726 	}
    727 	if (c == PEOF) {
    728 		if (*eofmark == '\0')
    729 			return (c);
    730 		synerror(EOFhere);
    731 	}
    732 	if (c == *eofmark) {
    733 		int c2;
    734 		char *q;
    735 
    736 		for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
    737 			;
    738 		if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
    739 			c = PEOF;
    740 			if (c2 == '\n') {
    741 				plinno++;
    742 				needprompt = doprompt;
    743 			}
    744 		} else {
    745 			pungetc();
    746 			pushstring(eofmark + 1, q - (eofmark + 1), NULL);
    747 		}
    748 	} else if (c == '\n' && *eofmark == '\0') {
    749 		c = PEOF;
    750 		plinno++;
    751 		needprompt = doprompt;
    752 	}
    753 	return (c);
    754 }
    755 
    756 
    757 /*
    758  * Input any here documents.
    759  */
    760 
    761 STATIC void
    762 slurp_heredoc(char *const eofmark, const int striptabs, const int sq)
    763 {
    764 	int c;
    765 	char *out;
    766 
    767 	c = pgetc();
    768 
    769 	/*
    770 	 * If we hit EOF on the input, and the eofmark is a null string ('')
    771 	 * we consider this empty line to be the eofmark, and exit without err.
    772 	 */
    773 	if (c == PEOF && *eofmark != '\0')
    774 		synerror(EOFhere);
    775 
    776 	STARTSTACKSTR(out);
    777 
    778 	while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
    779 		do {
    780 			if (sq) {
    781 				/*
    782 				 * in single quoted mode (eofmark quoted)
    783 				 * all we look for is \n so we can check
    784 				 * for the epfmark - everything saved literally.
    785 				 */
    786 				STPUTC(c, out);
    787 				if (c == '\n')
    788 					break;
    789 				continue;
    790 			}
    791 			/*
    792 			 * In double quoted (non-quoted eofmark)
    793 			 * we must handle \ followed by \n here
    794 			 * otherwise we can mismatch the end mark.
    795 			 * All other uses of \ will be handled later
    796 			 * when the here doc is expanded.
    797 			 *
    798 			 * This also makes sure \\ followed by \n does
    799 			 * not suppress the newline (the \ quotes itself)
    800 			 */
    801 			if (c == '\\') {		/* A backslash */
    802 				c = pgetc();		/* followed by */
    803 				if (c == '\n')		/* a newline?  */
    804 					continue;	/* y:drop both */
    805 				STPUTC('\\', out);	/* else keep \ */
    806 			}
    807 			STPUTC(c, out);			/* keep the char */
    808 			if (c == '\n')			/* at end of line */
    809 				break;			/* look for eofmark */
    810 
    811 		} while ((c = pgetc()) != PEOF);
    812 
    813 		/*
    814 		 * If we have read a line, and reached EOF, without
    815 		 * finding the eofmark, whether the EOF comes before
    816 		 * or immediately after the \n, that is an error.
    817 		 */
    818 		if (c == PEOF || (c = pgetc()) == PEOF)
    819 			synerror(EOFhere);
    820 	}
    821 	STPUTC('\0', out);
    822 
    823 	c = out - stackblock();
    824 	out = stackblock();
    825 	grabstackblock(c);
    826 	wordtext = out;
    827 
    828 	TRACE(("Slurped a heredoc (to '%s')%s: len %d, \"%.16s\"...\n",
    829 		eofmark, striptabs ? " tab stripped" : "", c, wordtext));
    830 }
    831 
    832 STATIC void
    833 readheredocs(void)
    834 {
    835 	struct heredoc *here;
    836 	union node *n;
    837 
    838 	while (heredoclist) {
    839 		here = heredoclist;
    840 		heredoclist = here->next;
    841 		if (needprompt) {
    842 			setprompt(2);
    843 			needprompt = 0;
    844 		}
    845 
    846 		slurp_heredoc(here->eofmark, here->striptabs,
    847 		    here->here->nhere.type == NHERE);
    848 
    849 		n = stalloc(sizeof(struct narg));
    850 		n->narg.type = NARG;
    851 		n->narg.next = NULL;
    852 		n->narg.text = wordtext;
    853 		n->narg.backquote = backquotelist;
    854 		here->here->nhere.doc = n;
    855 
    856 		if (here->here->nhere.type == NHERE)
    857 			continue;
    858 
    859 		/*
    860 		 * Now "parse" here docs that have unquoted eofmarkers.
    861 		 */
    862 		setinputstring(wordtext, 1);
    863 		readtoken1(pgetc(), DQSYNTAX, 1);
    864 		n->narg.text = wordtext;
    865 		n->narg.backquote = backquotelist;
    866 		popfile();
    867 	}
    868 }
    869 
    870 STATIC int
    871 peektoken(void)
    872 {
    873 	int t;
    874 
    875 	t = readtoken();
    876 	tokpushback++;
    877 	return (t);
    878 }
    879 
    880 STATIC int
    881 readtoken(void)
    882 {
    883 	int t;
    884 	int savecheckkwd = checkkwd;
    885 #ifdef DEBUG
    886 	int alreadyseen = tokpushback;
    887 #endif
    888 	struct alias *ap;
    889 
    890 	top:
    891 	t = xxreadtoken();
    892 
    893 	if (checkkwd) {
    894 		/*
    895 		 * eat newlines
    896 		 */
    897 		if (checkkwd == 2) {
    898 			checkkwd = 0;
    899 			while (t == TNL) {
    900 				readheredocs();
    901 				t = xxreadtoken();
    902 			}
    903 		} else
    904 			checkkwd = 0;
    905 		/*
    906 		 * check for keywords and aliases
    907 		 */
    908 		if (t == TWORD && !quoteflag) {
    909 			const char *const *pp;
    910 
    911 			for (pp = parsekwd; *pp; pp++) {
    912 				if (**pp == *wordtext && equal(*pp, wordtext)) {
    913 					lasttoken = t = pp -
    914 					    parsekwd + KWDOFFSET;
    915 					TRACE(("keyword %s recognized\n", tokname[t]));
    916 					goto out;
    917 				}
    918 			}
    919 			if (!noalias &&
    920 			    (ap = lookupalias(wordtext, 1)) != NULL) {
    921 				pushstring(ap->val, strlen(ap->val), ap);
    922 				checkkwd = savecheckkwd;
    923 				goto top;
    924 			}
    925 		}
    926 out:
    927 		checkkwd = (t == TNOT) ? savecheckkwd : 0;
    928 	}
    929 	TRACE(("%stoken %s %s\n", alreadyseen ? "reread " : "", tokname[t], t == TWORD ? wordtext : ""));
    930 	return (t);
    931 }
    932 
    933 
    934 /*
    935  * Read the next input token.
    936  * If the token is a word, we set backquotelist to the list of cmds in
    937  *	backquotes.  We set quoteflag to true if any part of the word was
    938  *	quoted.
    939  * If the token is TREDIR, then we set redirnode to a structure containing
    940  *	the redirection.
    941  * In all cases, the variable startlinno is set to the number of the line
    942  *	on which the token starts.
    943  *
    944  * [Change comment:  here documents and internal procedures]
    945  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
    946  *  word parsing code into a separate routine.  In this case, readtoken
    947  *  doesn't need to have any internal procedures, but parseword does.
    948  *  We could also make parseoperator in essence the main routine, and
    949  *  have parseword (readtoken1?) handle both words and redirection.]
    950  */
    951 
    952 #define RETURN(token)	return lasttoken = token
    953 
    954 STATIC int
    955 xxreadtoken(void)
    956 {
    957 	int c;
    958 
    959 	if (tokpushback) {
    960 		tokpushback = 0;
    961 		return lasttoken;
    962 	}
    963 	if (needprompt) {
    964 		setprompt(2);
    965 		needprompt = 0;
    966 	}
    967 	startlinno = plinno;
    968 	for (;;) {	/* until token or start of word found */
    969 		c = pgetc_macro();
    970 		switch (c) {
    971 		case ' ': case '\t':
    972 			continue;
    973 		case '#':
    974 			while ((c = pgetc()) != '\n' && c != PEOF)
    975 				continue;
    976 			pungetc();
    977 			continue;
    978 
    979 		case '\n':
    980 			plinno++;
    981 			needprompt = doprompt;
    982 			RETURN(TNL);
    983 		case PEOF:
    984 			RETURN(TEOF);
    985 
    986 		case '&':
    987 			if (pgetc() == '&')
    988 				RETURN(TAND);
    989 			pungetc();
    990 			RETURN(TBACKGND);
    991 		case '|':
    992 			if (pgetc() == '|')
    993 				RETURN(TOR);
    994 			pungetc();
    995 			RETURN(TPIPE);
    996 		case ';':
    997 			if (pgetc() == ';')
    998 				RETURN(TENDCASE);
    999 			pungetc();
   1000 			RETURN(TSEMI);
   1001 		case '(':
   1002 			RETURN(TLP);
   1003 		case ')':
   1004 			RETURN(TRP);
   1005 
   1006 		case '\\':
   1007 			switch (pgetc()) {
   1008 			case '\n':
   1009 				startlinno = ++plinno;
   1010 				if (doprompt)
   1011 					setprompt(2);
   1012 				else
   1013 					setprompt(0);
   1014 				continue;
   1015 			case PEOF:
   1016 				RETURN(TEOF);
   1017 			default:
   1018 				pungetc();
   1019 				break;
   1020 			}
   1021 			/* FALLTHROUGH */
   1022 		default:
   1023 			return readtoken1(c, BASESYNTAX, 0);
   1024 		}
   1025 	}
   1026 #undef RETURN
   1027 }
   1028 
   1029 
   1030 
   1031 /*
   1032  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
   1033  * is not NULL, read a here document.  In the latter case, eofmark is the
   1034  * word which marks the end of the document and striptabs is true if
   1035  * leading tabs should be stripped from the document.  The argument firstc
   1036  * is the first character of the input token or document.
   1037  *
   1038  * Because C does not have internal subroutines, I have simulated them
   1039  * using goto's to implement the subroutine linkage.  The following macros
   1040  * will run code that appears at the end of readtoken1.
   1041  */
   1042 
   1043 /*
   1044  * We used to remember only the current syntax, variable nesting level,
   1045  * double quote state for each var nesting level, and arith nesting
   1046  * level (unrelated to var nesting) and one prev syntax when in arith
   1047  * syntax.  This worked for simple cases, but can't handle arith inside
   1048  * var expansion inside arith inside var with some quoted and some not.
   1049  *
   1050  * Inspired by FreeBSD's implementation (though it was the obvious way)
   1051  * though implemented differently, we now have a stack that keeps track
   1052  * of what we are doing now, and what we were doing previously.
   1053  * Every time something changes, which will eventually end and should
   1054  * revert to the previous state, we push this stack, and then pop it
   1055  * again later (that is every ${} with an operator (to parse the word
   1056  * or pattern that follows) ${x} and $x are too simple to need it)
   1057  * $(( )) $( ) and "...".   Always.   Really, always!
   1058  *
   1059  * The stack is implemented as one static (on the C stack) base block
   1060  * containing LEVELS_PER_BLOCK (8) stack entries, which should be
   1061  * enough for the vast majority of cases.  For torture tests, we
   1062  * malloc more blocks as needed.  All accesses through the inline
   1063  * functions below.
   1064  */
   1065 
   1066 /*
   1067  * varnest & arinest will typically be 0 or 1
   1068  * (varnest can increment in usages like ${x=${y}} but probably
   1069  *  does not really need to)
   1070  * parenlevel allows balancing parens inside a $(( )), it is reset
   1071  * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
   1072  * quoted is special - we need to know 2 things ... are we inside "..."
   1073  * (even if inherited from some previous nesting level) and was there
   1074  * an opening '"' at this level (so the next will be closing).
   1075  * "..." can span nesting levels, but cannot be opened in one and
   1076  * closed in a different one.
   1077  * To handle this, "quoted" has two fields, the bottom 4 (really 2)
   1078  * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
   1079  * is really so special that this setting is not very important)
   1080  * and 0x10 that indicates that an opening quote has been seen.
   1081  * The bottom 4 bits are inherited, the 0x10 bit is not.
   1082  */
   1083 struct tokenstate {
   1084 	const char *ts_syntax;
   1085 	unsigned short ts_parenlevel;	/* counters */
   1086 	unsigned short ts_varnest;	/* 64000 levels should be enough! */
   1087 	unsigned short ts_arinest;
   1088 	unsigned short ts_quoted;	/* 1 -> single, 2 -> double */
   1089 };
   1090 
   1091 #define	NQ	0x00	/* Unquoted */
   1092 #define	SQ	0x01	/* Single Quotes */
   1093 #define	DQ	0x02	/* Double Quotes (or equivalent) */
   1094 #define	QF	0x0F		/* Mask to extract previous values */
   1095 #define	QS	0x10	/* Quoting started at this level in stack */
   1096 
   1097 #define	LEVELS_PER_BLOCK	8
   1098 #define	VSS			struct statestack
   1099 
   1100 struct statestack {
   1101 	VSS *prev;		/* previous block in list */
   1102 	int cur;		/* which of our tokenstates is current */
   1103 	struct tokenstate tokenstate[LEVELS_PER_BLOCK];
   1104 };
   1105 
   1106 static inline struct tokenstate *
   1107 currentstate(VSS *stack)
   1108 {
   1109 	return &stack->tokenstate[stack->cur];
   1110 }
   1111 
   1112 static inline struct tokenstate *
   1113 prevstate(VSS *stack)
   1114 {
   1115 	if (stack->cur != 0)
   1116 		return &stack->tokenstate[stack->cur - 1];
   1117 	if (stack->prev == NULL)	/* cannot drop below base */
   1118 		return &stack->tokenstate[0];
   1119 	return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
   1120 }
   1121 
   1122 static inline VSS *
   1123 bump_state_level(VSS *stack)
   1124 {
   1125 	struct tokenstate *os, *ts;
   1126 
   1127 	os = currentstate(stack);
   1128 
   1129 	if (++stack->cur >= LEVELS_PER_BLOCK) {
   1130 		VSS *ss;
   1131 
   1132 		ss = (VSS *)ckmalloc(sizeof (struct statestack));
   1133 		ss->cur = 0;
   1134 		ss->prev = stack;
   1135 		stack = ss;
   1136 	}
   1137 
   1138 	ts = currentstate(stack);
   1139 
   1140 	ts->ts_parenlevel = 0;	/* parens inside never match outside */
   1141 
   1142 	ts->ts_quoted  = os->ts_quoted & QF;	/* these are default settings */
   1143 	ts->ts_varnest = os->ts_varnest;
   1144 	ts->ts_arinest = os->ts_arinest;	/* when appropriate	   */
   1145 	ts->ts_syntax  = os->ts_syntax;		/*    they will be altered */
   1146 
   1147 	return stack;
   1148 }
   1149 
   1150 static inline VSS *
   1151 drop_state_level(VSS *stack)
   1152 {
   1153 	if (stack->cur == 0) {
   1154 		VSS *ss;
   1155 
   1156 		ss = stack;
   1157 		stack = ss->prev;
   1158 		if (stack == NULL)
   1159 			return ss;
   1160 		ckfree(ss);
   1161 	}
   1162 	--stack->cur;
   1163 	return stack;
   1164 }
   1165 
   1166 static inline void
   1167 cleanup_state_stack(VSS *stack)
   1168 {
   1169 	while (stack->prev != NULL) {
   1170 		stack->cur = 0;
   1171 		stack = drop_state_level(stack);
   1172 	}
   1173 }
   1174 
   1175 #define	PARSESUB()	{goto parsesub; parsesub_return:;}
   1176 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
   1177 
   1178 /*
   1179  * The following macros all assume the existance of a local var "stack"
   1180  * which contains a pointer to the current struct stackstate
   1181  */
   1182 
   1183 /*
   1184  * These are macros rather than inline funcs to avoid code churn as much
   1185  * as possible - they replace macros of the same name used previously.
   1186  */
   1187 #define	ISDBLQUOTE()	(currentstate(stack)->ts_quoted & QS)
   1188 #define	SETDBLQUOTE()	(currentstate(stack)->ts_quoted = QS | DQ)
   1189 #define	CLRDBLQUOTE()	(currentstate(stack)->ts_quoted =		\
   1190 			    stack->cur != 0 || stack->prev ?		\
   1191 				prevstate(stack)->ts_quoted & QF : 0)
   1192 
   1193 /*
   1194  * This set are just to avoid excess typing and line lengths...
   1195  * The ones that "look like" var names must be implemented to be lvalues
   1196  */
   1197 #define	syntax		(currentstate(stack)->ts_syntax)
   1198 #define	parenlevel	(currentstate(stack)->ts_parenlevel)
   1199 #define	varnest		(currentstate(stack)->ts_varnest)
   1200 #define	arinest		(currentstate(stack)->ts_arinest)
   1201 #define	quoted		(currentstate(stack)->ts_quoted)
   1202 #define	TS_PUSH()	(stack = bump_state_level(stack))
   1203 #define	TS_POP()	(stack = drop_state_level(stack))
   1204 
   1205 /*
   1206  * Called to parse command substitutions.  oldstyle is true if the command
   1207  * is enclosed inside `` (otherwise it was enclosed in "$( )")
   1208  *
   1209  * Internally nlpp is a pointer to the head of the linked
   1210  * list of commands (passed by reference), and savelen is the number of
   1211  * characters on the top of the stack which must be preserved.
   1212  */
   1213 static char *
   1214 parsebackq(VSS *const stack, char * const in,
   1215     struct nodelist **const pbqlist, const int oldstyle)
   1216 {
   1217 	struct nodelist **nlpp;
   1218 	const int savepbq = parsebackquote;
   1219 	union node *n;
   1220 	char *out;
   1221 	char *str = NULL;
   1222 	char *volatile sstr = str;
   1223 	struct jmploc jmploc;
   1224 	struct jmploc *const savehandler = handler;
   1225 	const int savelen = in - stackblock();
   1226 	int saveprompt;
   1227 
   1228 	if (setjmp(jmploc.loc)) {
   1229 		if (sstr)
   1230 			ckfree(__UNVOLATILE(sstr));
   1231 		cleanup_state_stack(stack);
   1232 		parsebackquote = 0;
   1233 		handler = savehandler;
   1234 		longjmp(handler->loc, 1);
   1235 	}
   1236 	INTOFF;
   1237 	sstr = str = NULL;
   1238 	if (savelen > 0) {
   1239 		sstr = str = ckmalloc(savelen);
   1240 		memcpy(str, stackblock(), savelen);
   1241 	}
   1242 	handler = &jmploc;
   1243 	INTON;
   1244         if (oldstyle) {
   1245                 /* We must read until the closing backquote, giving special
   1246                    treatment to some slashes, and then push the string and
   1247                    reread it as input, interpreting it normally.  */
   1248                 int pc;
   1249                 int psavelen;
   1250                 char *pstr;
   1251 
   1252 		/*
   1253 		 * Because the entire `...` is read here, we don't
   1254 		 * need to bother the state stack.  That will be used
   1255 		 * (as appropriate) when the processed string is re-read.
   1256 		 */
   1257                 STARTSTACKSTR(out);
   1258 		for (;;) {
   1259 			if (needprompt) {
   1260 				setprompt(2);
   1261 				needprompt = 0;
   1262 			}
   1263 			switch (pc = pgetc()) {
   1264 			case '`':
   1265 				goto done;
   1266 
   1267 			case '\\':
   1268                                 if ((pc = pgetc()) == '\n') {
   1269 					plinno++;
   1270 					if (doprompt)
   1271 						setprompt(2);
   1272 					else
   1273 						setprompt(0);
   1274 					/*
   1275 					 * If eating a newline, avoid putting
   1276 					 * the newline into the new character
   1277 					 * stream (via the STPUTC after the
   1278 					 * switch).
   1279 					 */
   1280 					continue;
   1281 				}
   1282                                 if (pc != '\\' && pc != '`' && pc != '$'
   1283                                     && (!ISDBLQUOTE() || pc != '"'))
   1284                                         STPUTC('\\', out);
   1285 				break;
   1286 
   1287 			case '\n':
   1288 				plinno++;
   1289 				needprompt = doprompt;
   1290 				break;
   1291 
   1292 			case PEOF:
   1293 			        startlinno = plinno;
   1294 				synerror("EOF in backquote substitution");
   1295  				break;
   1296 
   1297 			default:
   1298 				break;
   1299 			}
   1300 			STPUTC(pc, out);
   1301                 }
   1302 done:
   1303                 STPUTC('\0', out);
   1304                 psavelen = out - stackblock();
   1305                 if (psavelen > 0) {
   1306 			pstr = grabstackstr(out);
   1307 			setinputstring(pstr, 1);
   1308                 }
   1309         }
   1310 	nlpp = pbqlist;
   1311 	while (*nlpp)
   1312 		nlpp = &(*nlpp)->next;
   1313 	*nlpp = stalloc(sizeof(struct nodelist));
   1314 	(*nlpp)->next = NULL;
   1315 	parsebackquote = oldstyle;
   1316 
   1317 	if (oldstyle) {
   1318 		saveprompt = doprompt;
   1319 		doprompt = 0;
   1320 	} else
   1321 		saveprompt = 0;
   1322 
   1323 	n = list(0, oldstyle);
   1324 
   1325 	if (oldstyle)
   1326 		doprompt = saveprompt;
   1327 	else {
   1328 		if (readtoken() != TRP) {
   1329 			cleanup_state_stack(stack);
   1330 			synexpect(TRP, 0);
   1331 		}
   1332 	}
   1333 
   1334 	(*nlpp)->n = n;
   1335         if (oldstyle) {
   1336 		/*
   1337 		 * Start reading from old file again, ignoring any pushed back
   1338 		 * tokens left from the backquote parsing
   1339 		 */
   1340                 popfile();
   1341 		tokpushback = 0;
   1342 	}
   1343 
   1344 	while (stackblocksize() <= savelen)
   1345 		growstackblock();
   1346 	STARTSTACKSTR(out);
   1347 	if (str) {
   1348 		memcpy(out, str, savelen);
   1349 		STADJUST(savelen, out);
   1350 		INTOFF;
   1351 		ckfree(str);
   1352 		sstr = str = NULL;
   1353 		INTON;
   1354 	}
   1355 	parsebackquote = savepbq;
   1356 	handler = savehandler;
   1357 	if (arinest || ISDBLQUOTE())
   1358 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1359 	else
   1360 		USTPUTC(CTLBACKQ, out);
   1361 
   1362 	return out;
   1363 }
   1364 
   1365 /*
   1366  * Parse a redirection operator.  The parameter "out" points to a string
   1367  * specifying the fd to be redirected.  It is guaranteed to be either ""
   1368  * or a numeric string (for now anyway).  The parameter "c" contains the
   1369  * first character of the redirection operator.
   1370  *
   1371  * Note the string "out" is on the stack, which we are about to clobber,
   1372  * so process it first...
   1373  */
   1374 
   1375 static void
   1376 parseredir(const char *out,  int c)
   1377 {
   1378 	union node *np;
   1379 	int fd;
   1380 
   1381 	fd = (*out == '\0') ? -1 : atoi(out);
   1382 
   1383 	np = stalloc(sizeof(struct nfile));
   1384 	if (c == '>') {
   1385 		if (fd < 0)
   1386 			fd = 1;
   1387 		c = pgetc();
   1388 		if (c == '>')
   1389 			np->type = NAPPEND;
   1390 		else if (c == '|')
   1391 			np->type = NCLOBBER;
   1392 		else if (c == '&')
   1393 			np->type = NTOFD;
   1394 		else {
   1395 			np->type = NTO;
   1396 			pungetc();
   1397 		}
   1398 	} else {	/* c == '<' */
   1399 		if (fd < 0)
   1400 			fd = 0;
   1401 		switch (c = pgetc()) {
   1402 		case '<':
   1403 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
   1404 				np = stalloc(sizeof(struct nhere));
   1405 				np->nfile.fd = 0;
   1406 			}
   1407 			np->type = NHERE;
   1408 			heredoc = stalloc(sizeof(struct heredoc));
   1409 			heredoc->here = np;
   1410 			if ((c = pgetc()) == '-') {
   1411 				heredoc->striptabs = 1;
   1412 			} else {
   1413 				heredoc->striptabs = 0;
   1414 				pungetc();
   1415 			}
   1416 			break;
   1417 
   1418 		case '&':
   1419 			np->type = NFROMFD;
   1420 			break;
   1421 
   1422 		case '>':
   1423 			np->type = NFROMTO;
   1424 			break;
   1425 
   1426 		default:
   1427 			np->type = NFROM;
   1428 			pungetc();
   1429 			break;
   1430 		}
   1431 	}
   1432 	np->nfile.fd = fd;
   1433 
   1434 	redirnode = np;		/* this is the "value" of TRENODE */
   1435 }
   1436 
   1437 
   1438 /*
   1439  * The lowest level basic tokenizer.
   1440  *
   1441  * The next input byte (character) is in firstc, syn says which
   1442  * syntax tables we are to use (basic, single or double quoted, or arith)
   1443  * and magicq (used with sqsyntax and dqsyntax only) indicates that the
   1444  * quote character itself is not special (used parsing here docs and similar)
   1445  *
   1446  * The result is the type of the next token (its value, when there is one,
   1447  * is saved in the relevant global var - must fix that someday!) which is
   1448  * also saved for re-reading ("lasttoken").
   1449  *
   1450  * Overall, this routine does far more parsing than it is supposed to.
   1451  * That will also need fixing, someday...
   1452  */
   1453 STATIC int
   1454 readtoken1(int firstc, char const *syn, int magicq)
   1455 {
   1456 	int c;
   1457 	char * out;
   1458 	int len;
   1459 	struct nodelist *bqlist;
   1460 	int quotef;
   1461 	VSS static_stack;
   1462 	VSS *stack = &static_stack;
   1463 
   1464 	stack->prev = NULL;
   1465 	stack->cur = 0;
   1466 
   1467 	syntax = syn;
   1468 
   1469 	startlinno = plinno;
   1470 	varnest = 0;
   1471 	quoted = 0;
   1472 	if (syntax == DQSYNTAX)
   1473 		SETDBLQUOTE();
   1474 	quotef = 0;
   1475 	bqlist = NULL;
   1476 	arinest = 0;
   1477 	parenlevel = 0;
   1478 
   1479 	STARTSTACKSTR(out);
   1480 
   1481 	for (c = firstc ;; c = pgetc_macro()) {	/* until of token */
   1482 		CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
   1483 		switch (syntax[c]) {
   1484 		case CNL:	/* '\n' */
   1485 			if (syntax == BASESYNTAX)
   1486 				break;	/* exit loop */
   1487 			USTPUTC(c, out);
   1488 			plinno++;
   1489 			if (doprompt)
   1490 				setprompt(2);
   1491 			else
   1492 				setprompt(0);
   1493 			continue;
   1494 
   1495 		case CWORD:
   1496 			USTPUTC(c, out);
   1497 			continue;
   1498 		case CCTL:
   1499 			if (!magicq || ISDBLQUOTE())
   1500 				USTPUTC(CTLESC, out);
   1501 			USTPUTC(c, out);
   1502 			continue;
   1503 		case CBACK:	/* backslash */
   1504 			c = pgetc();
   1505 			if (c == PEOF) {
   1506 				USTPUTC('\\', out);
   1507 				pungetc();
   1508 				continue;
   1509 			}
   1510 			if (c == '\n') {
   1511 				plinno++;
   1512 				if (doprompt)
   1513 					setprompt(2);
   1514 				else
   1515 					setprompt(0);
   1516 				continue;
   1517 			}
   1518 			quotef = 1;	/* current token is quoted */
   1519 			if (ISDBLQUOTE() && c != '\\' && c != '`' &&
   1520 			    c != '$' && (c != '"' || magicq))
   1521 				USTPUTC('\\', out);
   1522 			if (SQSYNTAX[c] == CCTL)
   1523 				USTPUTC(CTLESC, out);
   1524 			else if (!magicq) {
   1525 				USTPUTC(CTLQUOTEMARK, out);
   1526 				USTPUTC(c, out);
   1527 				if (varnest != 0)
   1528 					USTPUTC(CTLQUOTEEND, out);
   1529 				continue;
   1530 			}
   1531 			USTPUTC(c, out);
   1532 			continue;
   1533 		case CSQUOTE:
   1534 			if (syntax != SQSYNTAX) {
   1535 				if (!magicq)
   1536 					USTPUTC(CTLQUOTEMARK, out);
   1537 				quotef = 1;
   1538 				TS_PUSH();
   1539 				syntax = SQSYNTAX;
   1540 				quoted = SQ;
   1541 				continue;
   1542 			}
   1543 			if (magicq && arinest == 0 && varnest == 0) {
   1544 				/* Ignore inside quoted here document */
   1545 				USTPUTC(c, out);
   1546 				continue;
   1547 			}
   1548 			/* End of single quotes... */
   1549 			TS_POP();
   1550 			if (syntax == BASESYNTAX && varnest != 0)
   1551 				USTPUTC(CTLQUOTEEND, out);
   1552 			continue;
   1553 		case CDQUOTE:
   1554 			if (magicq && arinest == 0 && varnest == 0) {
   1555 				/* Ignore inside here document */
   1556 				USTPUTC(c, out);
   1557 				continue;
   1558 			}
   1559 			quotef = 1;
   1560 			if (arinest) {
   1561 				if (ISDBLQUOTE()) {
   1562 					TS_POP();
   1563 				} else {
   1564 					TS_PUSH();
   1565 					syntax = DQSYNTAX;
   1566 					SETDBLQUOTE();
   1567 					USTPUTC(CTLQUOTEMARK, out);
   1568 				}
   1569 				continue;
   1570 			}
   1571 			if (magicq)
   1572 				continue;
   1573 			if (ISDBLQUOTE()) {
   1574 				TS_POP();
   1575 				if (varnest != 0)
   1576 					USTPUTC(CTLQUOTEEND, out);
   1577 			} else {
   1578 				TS_PUSH();
   1579 				syntax = DQSYNTAX;
   1580 				SETDBLQUOTE();
   1581 				USTPUTC(CTLQUOTEMARK, out);
   1582 			}
   1583 			continue;
   1584 		case CVAR:	/* '$' */
   1585 			PARSESUB();		/* parse substitution */
   1586 			continue;
   1587 		case CENDVAR:	/* CLOSEBRACE */
   1588 			if (varnest > 0 && !ISDBLQUOTE()) {
   1589 				TS_POP();
   1590 				USTPUTC(CTLENDVAR, out);
   1591 			} else {
   1592 				USTPUTC(c, out);
   1593 			}
   1594 			continue;
   1595 		case CLP:	/* '(' in arithmetic */
   1596 			parenlevel++;
   1597 			USTPUTC(c, out);
   1598 			continue;;
   1599 		case CRP:	/* ')' in arithmetic */
   1600 			if (parenlevel > 0) {
   1601 				USTPUTC(c, out);
   1602 				--parenlevel;
   1603 			} else {
   1604 				if (pgetc() == ')') {
   1605 					if (--arinest == 0) {
   1606 						TS_POP();
   1607 						USTPUTC(CTLENDARI, out);
   1608 					} else
   1609 						USTPUTC(')', out);
   1610 				} else {
   1611 					/*
   1612 					 * unbalanced parens
   1613 					 *  (don't 2nd guess - no error)
   1614 					 */
   1615 					pungetc();
   1616 					USTPUTC(')', out);
   1617 				}
   1618 			}
   1619 			continue;
   1620 		case CBQUOTE:	/* '`' */
   1621 			out = parsebackq(stack, out, &bqlist, 1);
   1622 			continue;
   1623 		case CEOF:		/* --> c == PEOF */
   1624 			break;		/* will exit loop */
   1625 		default:
   1626 			if (varnest == 0 && !ISDBLQUOTE())
   1627 				break;	/* exit loop */
   1628 			USTPUTC(c, out);
   1629 			continue;
   1630 		}
   1631 		break;	/* break from switch -> break from for loop too */
   1632 	}
   1633 
   1634 	if (syntax == ARISYNTAX) {
   1635 		cleanup_state_stack(stack);
   1636 		synerror("Missing '))'");
   1637 	}
   1638 	if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
   1639 		cleanup_state_stack(stack);
   1640 		synerror("Unterminated quoted string");
   1641 	}
   1642 	if (varnest != 0) {
   1643 		cleanup_state_stack(stack);
   1644 		startlinno = plinno;
   1645 		/* { */
   1646 		synerror("Missing '}'");
   1647 	}
   1648 
   1649 	USTPUTC('\0', out);
   1650 	len = out - stackblock();
   1651 	out = stackblock();
   1652 
   1653 	if (!magicq) {
   1654 		if ((c == '<' || c == '>')
   1655 		 && quotef == 0 && (*out == '\0' || is_number(out))) {
   1656 			parseredir(out, c);
   1657 			cleanup_state_stack(stack);
   1658 			return lasttoken = TREDIR;
   1659 		} else {
   1660 			pungetc();
   1661 		}
   1662 	}
   1663 
   1664 	quoteflag = quotef;
   1665 	backquotelist = bqlist;
   1666 	grabstackblock(len);
   1667 	wordtext = out;
   1668 	cleanup_state_stack(stack);
   1669 	return lasttoken = TWORD;
   1670 /* end of readtoken routine */
   1671 
   1672 
   1673 /*
   1674  * Parse a substitution.  At this point, we have read the dollar sign
   1675  * and nothing else.
   1676  */
   1677 
   1678 parsesub: {
   1679 	char buf[10];
   1680 	int subtype;
   1681 	int typeloc;
   1682 	int flags;
   1683 	char *p;
   1684 	static const char types[] = "}-+?=";
   1685 	int i;
   1686 	int linno;
   1687 
   1688 	c = pgetc();
   1689 	if (c != '(' && c != OPENBRACE && !is_name(c) && !is_special(c)) {
   1690 		USTPUTC('$', out);
   1691 		pungetc();
   1692 	} else if (c == '(') {	/* $(command) or $((arith)) */
   1693 		if (pgetc() == '(') {
   1694 			PARSEARITH();
   1695 		} else {
   1696 			pungetc();
   1697 			out = parsebackq(stack, out, &bqlist, 0);
   1698 		}
   1699 	} else {
   1700 		USTPUTC(CTLVAR, out);
   1701 		typeloc = out - stackblock();
   1702 		USTPUTC(VSNORMAL, out);
   1703 		subtype = VSNORMAL;
   1704 		flags = 0;
   1705 		if (c == OPENBRACE) {
   1706 			c = pgetc();
   1707 			if (c == '#') {
   1708 				if ((c = pgetc()) == CLOSEBRACE)
   1709 					c = '#';
   1710 				else
   1711 					subtype = VSLENGTH;
   1712 			}
   1713 			else
   1714 				subtype = 0;
   1715 		}
   1716 		if (is_name(c)) {
   1717 			p = out;
   1718 			do {
   1719 				STPUTC(c, out);
   1720 				c = pgetc();
   1721 			} while (is_in_name(c));
   1722 			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
   1723 				/* Replace the variable name with the
   1724 				 * current line number. */
   1725 				linno = plinno;
   1726 				if (funclinno != 0)
   1727 					linno -= funclinno - 1;
   1728 				snprintf(buf, sizeof(buf), "%d", linno);
   1729 				STADJUST(-6, out);
   1730 				for (i = 0; buf[i] != '\0'; i++)
   1731 					STPUTC(buf[i], out);
   1732 				flags |= VSLINENO;
   1733 			}
   1734 		} else if (is_digit(c)) {
   1735 			do {
   1736 				USTPUTC(c, out);
   1737 				c = pgetc();
   1738 			} while (subtype != VSNORMAL && is_digit(c));
   1739 		}
   1740 		else if (is_special(c)) {
   1741 			USTPUTC(c, out);
   1742 			c = pgetc();
   1743 		}
   1744 		else {
   1745 badsub:
   1746 			cleanup_state_stack(stack);
   1747 			synerror("Bad substitution");
   1748 		}
   1749 
   1750 		STPUTC('=', out);
   1751 		if (subtype == 0) {
   1752 			switch (c) {
   1753 			case ':':
   1754 				flags |= VSNUL;
   1755 				c = pgetc();
   1756 				/*FALLTHROUGH*/
   1757 			default:
   1758 				p = strchr(types, c);
   1759 				if (p == NULL)
   1760 					goto badsub;
   1761 				subtype = p - types + VSNORMAL;
   1762 				break;
   1763 			case '%':
   1764 			case '#':
   1765 				{
   1766 					int cc = c;
   1767 					subtype = c == '#' ? VSTRIMLEFT :
   1768 							     VSTRIMRIGHT;
   1769 					c = pgetc();
   1770 					if (c == cc)
   1771 						subtype++;
   1772 					else
   1773 						pungetc();
   1774 					break;
   1775 				}
   1776 			}
   1777 		} else {
   1778 			pungetc();
   1779 		}
   1780 		if (ISDBLQUOTE() || arinest)
   1781 			flags |= VSQUOTE;
   1782 		if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
   1783 			flags |= VSPATQ;
   1784 		*(stackblock() + typeloc) = subtype | flags;
   1785 		if (subtype != VSNORMAL) {
   1786 			TS_PUSH();
   1787 			varnest++;
   1788 			arinest = 0;
   1789 			if (subtype > VSASSIGN) {	/* # ## % %% */
   1790 				syntax = BASESYNTAX;
   1791 				CLRDBLQUOTE();
   1792 			}
   1793 		}
   1794 	}
   1795 	goto parsesub_return;
   1796 }
   1797 
   1798 
   1799 /*
   1800  * Parse an arithmetic expansion (indicate start of one and set state)
   1801  */
   1802 parsearith: {
   1803 
   1804 	if (syntax == ARISYNTAX) {
   1805 		/*
   1806 		 * we collapse embedded arithmetic expansion to
   1807 		 * parentheses, which should be equivalent
   1808 		 */
   1809 		USTPUTC('(', out);
   1810 		USTPUTC('(', out);
   1811 		/*
   1812 		 * Need 2 of them because there will (should be)
   1813 		 * two closing ))'s to follow later.
   1814 		 */
   1815 		parenlevel += 2;
   1816 	} else {
   1817 		TS_PUSH();
   1818 		syntax = ARISYNTAX;
   1819 		++arinest;
   1820 		varnest = 0;
   1821 
   1822 		USTPUTC(CTLARI, out);
   1823 		if (ISDBLQUOTE())
   1824 			USTPUTC('"',out);
   1825 		else
   1826 			USTPUTC(' ',out);
   1827 	}
   1828 	goto parsearith_return;
   1829 }
   1830 
   1831 } /* end of readtoken */
   1832 
   1833 
   1834 
   1835 #ifdef mkinit
   1836 RESET {
   1837 	tokpushback = 0;
   1838 	checkkwd = 0;
   1839 }
   1840 #endif
   1841 
   1842 /*
   1843  * Returns true if the text contains nothing to expand (no dollar signs
   1844  * or backquotes).
   1845  */
   1846 
   1847 STATIC int
   1848 noexpand(char *text)
   1849 {
   1850 	char *p;
   1851 	char c;
   1852 
   1853 	p = text;
   1854 	while ((c = *p++) != '\0') {
   1855 		if (c == CTLQUOTEMARK)
   1856 			continue;
   1857 		if (c == CTLESC)
   1858 			p++;
   1859 		else if (BASESYNTAX[(int)c] == CCTL)
   1860 			return 0;
   1861 	}
   1862 	return 1;
   1863 }
   1864 
   1865 
   1866 /*
   1867  * Return true if the argument is a legal variable name (a letter or
   1868  * underscore followed by zero or more letters, underscores, and digits).
   1869  */
   1870 
   1871 int
   1872 goodname(char *name)
   1873 {
   1874 	char *p;
   1875 
   1876 	p = name;
   1877 	if (! is_name(*p))
   1878 		return 0;
   1879 	while (*++p) {
   1880 		if (! is_in_name(*p))
   1881 			return 0;
   1882 	}
   1883 	return 1;
   1884 }
   1885 
   1886 
   1887 /*
   1888  * Called when an unexpected token is read during the parse.  The argument
   1889  * is the token that is expected, or -1 if more than one type of token can
   1890  * occur at this point.
   1891  */
   1892 
   1893 STATIC void
   1894 synexpect(int token, const char *text)
   1895 {
   1896 	char msg[64];
   1897 	char *p;
   1898 
   1899 	if (lasttoken == TWORD) {
   1900 		size_t len = strlen(wordtext);
   1901 
   1902 		if (len <= 13)
   1903 			fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
   1904 		else
   1905 			fmtstr(msg, 34,
   1906 			    "Word \"%.10s...\" unexpected", wordtext);
   1907 	} else
   1908 		fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
   1909 
   1910 	p = strchr(msg, '\0');
   1911 	if (text)
   1912 		fmtstr(p, 30, " (expecting \"%.10s\")", text);
   1913 	else if (token >= 0)
   1914 		fmtstr(p, 30, " (expecting %s)",  tokname[token]);
   1915 
   1916 	synerror(msg);
   1917 	/* NOTREACHED */
   1918 }
   1919 
   1920 
   1921 STATIC void
   1922 synerror(const char *msg)
   1923 {
   1924 	error("%d: Syntax error: %s\n", startlinno, msg);
   1925 	/* NOTREACHED */
   1926 }
   1927 
   1928 STATIC void
   1929 setprompt(int which)
   1930 {
   1931 	whichprompt = which;
   1932 
   1933 #ifndef SMALL
   1934 	if (!el)
   1935 #endif
   1936 		out2str(getprompt(NULL));
   1937 }
   1938 
   1939 /*
   1940  * called by editline -- any expansions to the prompt
   1941  *    should be added here.
   1942  */
   1943 const char *
   1944 getprompt(void *unused)
   1945 {
   1946 	switch (whichprompt) {
   1947 	case 0:
   1948 		return "";
   1949 	case 1:
   1950 		return ps1val();
   1951 	case 2:
   1952 		return ps2val();
   1953 	default:
   1954 		return "<internal prompt error>";
   1955 	}
   1956 }
   1957