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