parser.c revision 1.135 1 /* $NetBSD: parser.c,v 1.135 2017/06/07 08:10:31 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.135 2017/06/07 08:10:31 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;
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;
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;
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;
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;
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;
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.lineno = startlinno;
727 n->narg.backquote = backquotelist;
728 n->narg.lineno = startlinno - elided_nl;
729 return n;
730 }
731
732 void
733 fixredir(union node *n, const char *text, int err)
734 {
735
736 VTRACE(DBG_PARSE, ("Fix redir %s %d\n", text, err));
737 if (!err)
738 n->ndup.vname = NULL;
739
740 if (is_number(text))
741 n->ndup.dupfd = number(text);
742 else if (text[0] == '-' && text[1] == '\0')
743 n->ndup.dupfd = -1;
744 else {
745
746 if (err)
747 synerror("Bad fd number");
748 else
749 n->ndup.vname = makename();
750 }
751 }
752
753
754 STATIC void
755 parsefname(void)
756 {
757 union node *n = redirnode;
758
759 if (readtoken() != TWORD)
760 synexpect(-1, 0);
761 if (n->type == NHERE) {
762 struct heredoc *here = heredoc;
763 struct heredoc *p;
764
765 if (quoteflag == 0)
766 n->type = NXHERE;
767 VTRACE(DBG_PARSE, ("Here document %d @%d\n", n->type, plinno));
768 if (here->striptabs) {
769 while (*wordtext == '\t')
770 wordtext++;
771 }
772
773 /*
774 * this test is not really necessary, we are not
775 * required to expand wordtext, but there's no reason
776 * it cannot be $$ or something like that - that would
777 * not mean the pid, but literally two '$' characters.
778 * There is no need for limits on what the word can be.
779 * However, it needs to stay literal as entered, not
780 * have $ converted to CTLVAR or something, which as
781 * the parser is, at the minute, is impossible to prevent.
782 * So, leave it like this until the rest of the parser is fixed.
783 */
784 if (!noexpand(wordtext))
785 synerror("Illegal eof marker for << redirection");
786
787 rmescapes(wordtext);
788 here->eofmark = wordtext;
789 here->next = NULL;
790 if (heredoclist == NULL)
791 heredoclist = here;
792 else {
793 for (p = heredoclist ; p->next ; p = p->next)
794 continue;
795 p->next = here;
796 }
797 } else if (n->type == NTOFD || n->type == NFROMFD) {
798 fixredir(n, wordtext, 0);
799 } else {
800 n->nfile.fname = makename();
801 }
802 }
803
804 /*
805 * Check to see whether we are at the end of the here document. When this
806 * is called, c is set to the first character of the next input line. If
807 * we are at the end of the here document, this routine sets the c to PEOF.
808 * The new value of c is returned.
809 */
810
811 static int
812 checkend(int c, char * const eofmark, const int striptabs)
813 {
814
815 if (striptabs) {
816 while (c == '\t')
817 c = pgetc();
818 }
819 if (c == PEOF) {
820 if (*eofmark == '\0')
821 return (c);
822 synerror(EOFhere);
823 }
824 if (c == *eofmark) {
825 int c2;
826 char *q;
827
828 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
829 ;
830 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
831 c = PEOF;
832 if (c2 == '\n') {
833 plinno++;
834 needprompt = doprompt;
835 }
836 } else {
837 pungetc();
838 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
839 }
840 } else if (c == '\n' && *eofmark == '\0') {
841 c = PEOF;
842 plinno++;
843 needprompt = doprompt;
844 }
845 return (c);
846 }
847
848
849 /*
850 * Input any here documents.
851 */
852
853 STATIC int
854 slurp_heredoc(char *const eofmark, const int striptabs, const int sq)
855 {
856 int c;
857 char *out;
858 int lines = plinno;
859
860 c = pgetc();
861
862 /*
863 * If we hit EOF on the input, and the eofmark is a null string ('')
864 * we consider this empty line to be the eofmark, and exit without err.
865 */
866 if (c == PEOF && *eofmark != '\0')
867 synerror(EOFhere);
868
869 STARTSTACKSTR(out);
870
871 while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
872 do {
873 if (sq) {
874 /*
875 * in single quoted mode (eofmark quoted)
876 * all we look for is \n so we can check
877 * for the epfmark - everything saved literally.
878 */
879 STPUTC(c, out);
880 if (c == '\n') {
881 plinno++;
882 break;
883 }
884 continue;
885 }
886 /*
887 * In double quoted (non-quoted eofmark)
888 * we must handle \ followed by \n here
889 * otherwise we can mismatch the end mark.
890 * All other uses of \ will be handled later
891 * when the here doc is expanded.
892 *
893 * This also makes sure \\ followed by \n does
894 * not suppress the newline (the \ quotes itself)
895 */
896 if (c == '\\') { /* A backslash */
897 c = pgetc(); /* followed by */
898 if (c == '\n') { /* a newline? */
899 /*XXX CTLNONL ?? XXX*/
900 plinno++;
901 continue; /* :drop both */
902 }
903 STPUTC('\\', out); /* else keep \ */
904 }
905 STPUTC(c, out); /* keep the char */
906 if (c == '\n') { /* at end of line */
907 plinno++;
908 break; /* look for eofmark */
909 }
910 } while ((c = pgetc()) != PEOF);
911
912 /*
913 * If we have read a line, and reached EOF, without
914 * finding the eofmark, whether the EOF comes before
915 * or immediately after the \n, that is an error.
916 */
917 if (c == PEOF || (c = pgetc()) == PEOF)
918 synerror(EOFhere);
919 }
920 STPUTC('\0', out);
921
922 c = out - stackblock();
923 out = stackblock();
924 grabstackblock(c);
925 wordtext = out;
926
927 VTRACE(DBG_PARSE,
928 ("Slurped a %d line %sheredoc (to '%s')%s: len %d, \"%.*s%s\" @%d\n",
929 plinno - lines, sq ? "quoted " : "", eofmark,
930 striptabs ? " tab stripped" : "", c, (c > 16 ? 16 : c),
931 wordtext, (c > 16 ? "..." : ""), plinno));
932
933 return (plinno - lines);
934 }
935
936 static char *
937 insert_elided_nl(char *str)
938 {
939 while (elided_nl > 0) {
940 STPUTC(CTLNONL, str);
941 elided_nl--;
942 }
943 return str;
944 }
945
946 STATIC void
947 readheredocs(void)
948 {
949 struct heredoc *here;
950 union node *n;
951 int line, l;
952
953 line = 0; /*XXX - gcc! obviously unneeded */
954 if (heredoclist)
955 line = heredoclist->startline + 1;
956 l = 0;
957 while (heredoclist) {
958 line += l;
959 here = heredoclist;
960 heredoclist = here->next;
961 if (needprompt) {
962 setprompt(2);
963 needprompt = 0;
964 }
965
966 l = slurp_heredoc(here->eofmark, here->striptabs,
967 here->here->nhere.type == NHERE);
968
969 n = stalloc(sizeof(struct narg));
970 n->narg.type = NARG;
971 n->narg.next = NULL;
972 n->narg.text = wordtext;
973 n->narg.lineno = line;
974 n->narg.backquote = backquotelist;
975 here->here->nhere.doc = n;
976
977 if (here->here->nhere.type == NHERE)
978 continue;
979
980 /*
981 * Now "parse" here docs that have unquoted eofmarkers.
982 */
983 setinputstring(wordtext, 1, line);
984 readtoken1(pgetc(), DQSYNTAX, 1);
985 n->narg.text = wordtext;
986 n->narg.backquote = backquotelist;
987 popfile();
988 }
989 }
990
991 STATIC int
992 peektoken(void)
993 {
994 int t;
995
996 t = readtoken();
997 tokpushback++;
998 return (t);
999 }
1000
1001 STATIC int
1002 readtoken(void)
1003 {
1004 int t;
1005 int savecheckkwd = checkkwd;
1006 #ifdef DEBUG
1007 int alreadyseen = tokpushback;
1008 #endif
1009 struct alias *ap;
1010
1011 top:
1012 t = xxreadtoken();
1013
1014 if (checkkwd) {
1015 /*
1016 * eat newlines
1017 */
1018 if (checkkwd == 2) {
1019 checkkwd = 0;
1020 while (t == TNL) {
1021 readheredocs();
1022 t = xxreadtoken();
1023 }
1024 } else
1025 checkkwd = 0;
1026 /*
1027 * check for keywords and aliases
1028 */
1029 if (t == TWORD && !quoteflag) {
1030 const char *const *pp;
1031
1032 for (pp = parsekwd; *pp; pp++) {
1033 if (**pp == *wordtext && equal(*pp, wordtext)) {
1034 lasttoken = t = pp -
1035 parsekwd + KWDOFFSET;
1036 VTRACE(DBG_PARSE,
1037 ("keyword %s recognized @%d\n",
1038 tokname[t], plinno));
1039 goto out;
1040 }
1041 }
1042 if (!noalias &&
1043 (ap = lookupalias(wordtext, 1)) != NULL) {
1044 pushstring(ap->val, strlen(ap->val), ap);
1045 checkkwd = savecheckkwd;
1046 goto top;
1047 }
1048 }
1049 out:
1050 checkkwd = (t == TNOT) ? savecheckkwd : 0;
1051 }
1052 VTRACE(DBG_PARSE, ("%stoken %s %s @%d\n", alreadyseen ? "reread " : "",
1053 tokname[t], t == TWORD ? wordtext : "", plinno));
1054 return (t);
1055 }
1056
1057
1058 /*
1059 * Read the next input token.
1060 * If the token is a word, we set backquotelist to the list of cmds in
1061 * backquotes. We set quoteflag to true if any part of the word was
1062 * quoted.
1063 * If the token is TREDIR, then we set redirnode to a structure containing
1064 * the redirection.
1065 * In all cases, the variable startlinno is set to the number of the line
1066 * on which the token starts.
1067 *
1068 * [Change comment: here documents and internal procedures]
1069 * [Readtoken shouldn't have any arguments. Perhaps we should make the
1070 * word parsing code into a separate routine. In this case, readtoken
1071 * doesn't need to have any internal procedures, but parseword does.
1072 * We could also make parseoperator in essence the main routine, and
1073 * have parseword (readtoken1?) handle both words and redirection.]
1074 */
1075
1076 #define RETURN(token) return lasttoken = token
1077
1078 STATIC int
1079 xxreadtoken(void)
1080 {
1081 int c;
1082
1083 if (tokpushback) {
1084 tokpushback = 0;
1085 return lasttoken;
1086 }
1087 if (needprompt) {
1088 setprompt(2);
1089 needprompt = 0;
1090 }
1091 elided_nl = 0;
1092 startlinno = plinno;
1093 for (;;) { /* until token or start of word found */
1094 c = pgetc_macro();
1095 switch (c) {
1096 case ' ': case '\t':
1097 continue;
1098 case '#':
1099 while ((c = pgetc()) != '\n' && c != PEOF)
1100 continue;
1101 pungetc();
1102 continue;
1103
1104 case '\n':
1105 plinno++;
1106 needprompt = doprompt;
1107 RETURN(TNL);
1108 case PEOF:
1109 RETURN(TEOF);
1110
1111 case '&':
1112 if (pgetc_linecont() == '&')
1113 RETURN(TAND);
1114 pungetc();
1115 RETURN(TBACKGND);
1116 case '|':
1117 if (pgetc_linecont() == '|')
1118 RETURN(TOR);
1119 pungetc();
1120 RETURN(TPIPE);
1121 case ';':
1122 switch (pgetc_linecont()) {
1123 case ';':
1124 RETURN(TENDCASE);
1125 case '&':
1126 RETURN(TCASEFALL);
1127 default:
1128 pungetc();
1129 RETURN(TSEMI);
1130 }
1131 case '(':
1132 RETURN(TLP);
1133 case ')':
1134 RETURN(TRP);
1135
1136 case '\\':
1137 switch (pgetc()) {
1138 case '\n':
1139 startlinno = ++plinno;
1140 if (doprompt)
1141 setprompt(2);
1142 else
1143 setprompt(0);
1144 continue;
1145 case PEOF:
1146 RETURN(TEOF);
1147 default:
1148 pungetc();
1149 break;
1150 }
1151 /* FALLTHROUGH */
1152 default:
1153 return readtoken1(c, BASESYNTAX, 0);
1154 }
1155 }
1156 #undef RETURN
1157 }
1158
1159
1160
1161 /*
1162 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1163 * is not NULL, read a here document. In the latter case, eofmark is the
1164 * word which marks the end of the document and striptabs is true if
1165 * leading tabs should be stripped from the document. The argument firstc
1166 * is the first character of the input token or document.
1167 *
1168 * Because C does not have internal subroutines, I have simulated them
1169 * using goto's to implement the subroutine linkage. The following macros
1170 * will run code that appears at the end of readtoken1.
1171 */
1172
1173 /*
1174 * We used to remember only the current syntax, variable nesting level,
1175 * double quote state for each var nesting level, and arith nesting
1176 * level (unrelated to var nesting) and one prev syntax when in arith
1177 * syntax. This worked for simple cases, but can't handle arith inside
1178 * var expansion inside arith inside var with some quoted and some not.
1179 *
1180 * Inspired by FreeBSD's implementation (though it was the obvious way)
1181 * though implemented differently, we now have a stack that keeps track
1182 * of what we are doing now, and what we were doing previously.
1183 * Every time something changes, which will eventually end and should
1184 * revert to the previous state, we push this stack, and then pop it
1185 * again later (that is every ${} with an operator (to parse the word
1186 * or pattern that follows) ${x} and $x are too simple to need it)
1187 * $(( )) $( ) and "...". Always. Really, always!
1188 *
1189 * The stack is implemented as one static (on the C stack) base block
1190 * containing LEVELS_PER_BLOCK (8) stack entries, which should be
1191 * enough for the vast majority of cases. For torture tests, we
1192 * malloc more blocks as needed. All accesses through the inline
1193 * functions below.
1194 */
1195
1196 /*
1197 * varnest & arinest will typically be 0 or 1
1198 * (varnest can increment in usages like ${x=${y}} but probably
1199 * does not really need to)
1200 * parenlevel allows balancing parens inside a $(( )), it is reset
1201 * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
1202 * quoted is special - we need to know 2 things ... are we inside "..."
1203 * (even if inherited from some previous nesting level) and was there
1204 * an opening '"' at this level (so the next will be closing).
1205 * "..." can span nesting levels, but cannot be opened in one and
1206 * closed in a different one.
1207 * To handle this, "quoted" has two fields, the bottom 4 (really 2)
1208 * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
1209 * is really so special that this setting is not very important)
1210 * and 0x10 that indicates that an opening quote has been seen.
1211 * The bottom 4 bits are inherited, the 0x10 bit is not.
1212 */
1213 struct tokenstate {
1214 const char *ts_syntax;
1215 unsigned short ts_parenlevel; /* counters */
1216 unsigned short ts_varnest; /* 64000 levels should be enough! */
1217 unsigned short ts_arinest;
1218 unsigned short ts_quoted; /* 1 -> single, 2 -> double */
1219 };
1220
1221 #define NQ 0x00 /* Unquoted */
1222 #define SQ 0x01 /* Single Quotes */
1223 #define DQ 0x02 /* Double Quotes (or equivalent) */
1224 #define QF 0x0F /* Mask to extract previous values */
1225 #define QS 0x10 /* Quoting started at this level in stack */
1226
1227 #define LEVELS_PER_BLOCK 8
1228 #define VSS struct statestack
1229
1230 struct statestack {
1231 VSS *prev; /* previous block in list */
1232 int cur; /* which of our tokenstates is current */
1233 struct tokenstate tokenstate[LEVELS_PER_BLOCK];
1234 };
1235
1236 static inline struct tokenstate *
1237 currentstate(VSS *stack)
1238 {
1239 return &stack->tokenstate[stack->cur];
1240 }
1241
1242 static inline struct tokenstate *
1243 prevstate(VSS *stack)
1244 {
1245 if (stack->cur != 0)
1246 return &stack->tokenstate[stack->cur - 1];
1247 if (stack->prev == NULL) /* cannot drop below base */
1248 return &stack->tokenstate[0];
1249 return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
1250 }
1251
1252 static inline VSS *
1253 bump_state_level(VSS *stack)
1254 {
1255 struct tokenstate *os, *ts;
1256
1257 os = currentstate(stack);
1258
1259 if (++stack->cur >= LEVELS_PER_BLOCK) {
1260 VSS *ss;
1261
1262 ss = (VSS *)ckmalloc(sizeof (struct statestack));
1263 ss->cur = 0;
1264 ss->prev = stack;
1265 stack = ss;
1266 }
1267
1268 ts = currentstate(stack);
1269
1270 ts->ts_parenlevel = 0; /* parens inside never match outside */
1271
1272 ts->ts_quoted = os->ts_quoted & QF; /* these are default settings */
1273 ts->ts_varnest = os->ts_varnest;
1274 ts->ts_arinest = os->ts_arinest; /* when appropriate */
1275 ts->ts_syntax = os->ts_syntax; /* they will be altered */
1276
1277 return stack;
1278 }
1279
1280 static inline VSS *
1281 drop_state_level(VSS *stack)
1282 {
1283 if (stack->cur == 0) {
1284 VSS *ss;
1285
1286 ss = stack;
1287 stack = ss->prev;
1288 if (stack == NULL)
1289 return ss;
1290 ckfree(ss);
1291 }
1292 --stack->cur;
1293 return stack;
1294 }
1295
1296 static inline void
1297 cleanup_state_stack(VSS *stack)
1298 {
1299 while (stack->prev != NULL) {
1300 stack->cur = 0;
1301 stack = drop_state_level(stack);
1302 }
1303 }
1304
1305 #define PARSESUB() {goto parsesub; parsesub_return:;}
1306 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1307
1308 /*
1309 * The following macros all assume the existance of a local var "stack"
1310 * which contains a pointer to the current struct stackstate
1311 */
1312
1313 /*
1314 * These are macros rather than inline funcs to avoid code churn as much
1315 * as possible - they replace macros of the same name used previously.
1316 */
1317 #define ISDBLQUOTE() (currentstate(stack)->ts_quoted & QS)
1318 #define SETDBLQUOTE() (currentstate(stack)->ts_quoted = QS | DQ)
1319 #define CLRDBLQUOTE() (currentstate(stack)->ts_quoted = \
1320 stack->cur != 0 || stack->prev ? \
1321 prevstate(stack)->ts_quoted & QF : 0)
1322
1323 /*
1324 * This set are just to avoid excess typing and line lengths...
1325 * The ones that "look like" var names must be implemented to be lvalues
1326 */
1327 #define syntax (currentstate(stack)->ts_syntax)
1328 #define parenlevel (currentstate(stack)->ts_parenlevel)
1329 #define varnest (currentstate(stack)->ts_varnest)
1330 #define arinest (currentstate(stack)->ts_arinest)
1331 #define quoted (currentstate(stack)->ts_quoted)
1332 #define TS_PUSH() (stack = bump_state_level(stack))
1333 #define TS_POP() (stack = drop_state_level(stack))
1334
1335 /*
1336 * Called to parse command substitutions. oldstyle is true if the command
1337 * is enclosed inside `` (otherwise it was enclosed in "$( )")
1338 *
1339 * Internally nlpp is a pointer to the head of the linked
1340 * list of commands (passed by reference), and savelen is the number of
1341 * characters on the top of the stack which must be preserved.
1342 */
1343 static char *
1344 parsebackq(VSS *const stack, char * const in,
1345 struct nodelist **const pbqlist, const int oldstyle)
1346 {
1347 struct nodelist **nlpp;
1348 const int savepbq = parsebackquote;
1349 union node *n;
1350 char *out;
1351 char *str = NULL;
1352 char *volatile sstr = str;
1353 struct jmploc jmploc;
1354 struct jmploc *const savehandler = handler;
1355 const int savelen = in - stackblock();
1356 int saveprompt;
1357
1358 if (setjmp(jmploc.loc)) {
1359 if (sstr)
1360 ckfree(__UNVOLATILE(sstr));
1361 cleanup_state_stack(stack);
1362 parsebackquote = 0;
1363 handler = savehandler;
1364 longjmp(handler->loc, 1);
1365 }
1366 INTOFF;
1367 sstr = str = NULL;
1368 if (savelen > 0) {
1369 sstr = str = ckmalloc(savelen);
1370 memcpy(str, stackblock(), savelen);
1371 }
1372 handler = &jmploc;
1373 INTON;
1374 if (oldstyle) {
1375 /*
1376 * We must read until the closing backquote, giving special
1377 * treatment to some slashes, and then push the string and
1378 * reread it as input, interpreting it normally.
1379 */
1380 int pc;
1381 int psavelen;
1382 char *pstr;
1383 int line1 = plinno;
1384
1385 /*
1386 * Because the entire `...` is read here, we don't
1387 * need to bother the state stack. That will be used
1388 * (as appropriate) when the processed string is re-read.
1389 */
1390 STARTSTACKSTR(out);
1391 for (;;) {
1392 if (needprompt) {
1393 setprompt(2);
1394 needprompt = 0;
1395 }
1396 pc = pgetc_linecont();
1397 if (pc == '`')
1398 break;
1399 switch (pc) {
1400 case '\\':
1401 pc = pgetc(); /* cannot be '\n' */
1402 if (pc != '\\' && pc != '`' && pc != '$'
1403 && (!ISDBLQUOTE() || pc != '"'))
1404 STPUTC('\\', out);
1405 break;
1406
1407 case '\n':
1408 plinno++;
1409 out = insert_elided_nl(out);
1410 needprompt = doprompt;
1411 break;
1412
1413 case PEOF:
1414 startlinno = plinno;
1415 synerror("EOF in backquote substitution");
1416 break;
1417
1418 default:
1419 break;
1420 }
1421 STPUTC(pc, out);
1422 }
1423 STPUTC('\0', out);
1424 psavelen = out - stackblock();
1425 if (psavelen > 0) {
1426 pstr = grabstackstr(out);
1427 setinputstring(pstr, 1, line1);
1428 }
1429 }
1430 nlpp = pbqlist;
1431 while (*nlpp)
1432 nlpp = &(*nlpp)->next;
1433 *nlpp = stalloc(sizeof(struct nodelist));
1434 (*nlpp)->next = NULL;
1435 parsebackquote = oldstyle;
1436
1437 if (oldstyle) {
1438 saveprompt = doprompt;
1439 doprompt = 0;
1440 } else
1441 saveprompt = 0;
1442
1443 n = list(0, oldstyle);
1444
1445 if (oldstyle)
1446 doprompt = saveprompt;
1447 else {
1448 if (readtoken() != TRP) {
1449 cleanup_state_stack(stack);
1450 synexpect(TRP, 0);
1451 }
1452 }
1453
1454 (*nlpp)->n = n;
1455 if (oldstyle) {
1456 /*
1457 * Start reading from old file again, ignoring any pushed back
1458 * tokens left from the backquote parsing
1459 */
1460 popfile();
1461 tokpushback = 0;
1462 }
1463
1464 while (stackblocksize() <= savelen)
1465 growstackblock();
1466 STARTSTACKSTR(out);
1467 if (str) {
1468 memcpy(out, str, savelen);
1469 STADJUST(savelen, out);
1470 INTOFF;
1471 ckfree(str);
1472 sstr = str = NULL;
1473 INTON;
1474 }
1475 parsebackquote = savepbq;
1476 handler = savehandler;
1477 if (arinest || ISDBLQUOTE())
1478 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1479 else
1480 USTPUTC(CTLBACKQ, out);
1481
1482 return out;
1483 }
1484
1485 /*
1486 * Parse a redirection operator. The parameter "out" points to a string
1487 * specifying the fd to be redirected. It is guaranteed to be either ""
1488 * or a numeric string (for now anyway). The parameter "c" contains the
1489 * first character of the redirection operator.
1490 *
1491 * Note the string "out" is on the stack, which we are about to clobber,
1492 * so process it first...
1493 */
1494
1495 static void
1496 parseredir(const char *out, int c)
1497 {
1498 union node *np;
1499 int fd;
1500
1501 fd = (*out == '\0') ? -1 : atoi(out);
1502
1503 np = stalloc(sizeof(struct nfile));
1504 if (c == '>') {
1505 if (fd < 0)
1506 fd = 1;
1507 c = pgetc_linecont();
1508 if (c == '>')
1509 np->type = NAPPEND;
1510 else if (c == '|')
1511 np->type = NCLOBBER;
1512 else if (c == '&')
1513 np->type = NTOFD;
1514 else {
1515 np->type = NTO;
1516 pungetc();
1517 }
1518 } else { /* c == '<' */
1519 if (fd < 0)
1520 fd = 0;
1521 switch (c = pgetc_linecont()) {
1522 case '<':
1523 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1524 np = stalloc(sizeof(struct nhere));
1525 np->nfile.fd = 0;
1526 }
1527 np->type = NHERE;
1528 heredoc = stalloc(sizeof(struct heredoc));
1529 heredoc->here = np;
1530 heredoc->startline = plinno;
1531 if ((c = pgetc_linecont()) == '-') {
1532 heredoc->striptabs = 1;
1533 } else {
1534 heredoc->striptabs = 0;
1535 pungetc();
1536 }
1537 break;
1538
1539 case '&':
1540 np->type = NFROMFD;
1541 break;
1542
1543 case '>':
1544 np->type = NFROMTO;
1545 break;
1546
1547 default:
1548 np->type = NFROM;
1549 pungetc();
1550 break;
1551 }
1552 }
1553 np->nfile.fd = fd;
1554
1555 redirnode = np; /* this is the "value" of TRENODE */
1556 }
1557
1558
1559 /*
1560 * The lowest level basic tokenizer.
1561 *
1562 * The next input byte (character) is in firstc, syn says which
1563 * syntax tables we are to use (basic, single or double quoted, or arith)
1564 * and magicq (used with sqsyntax and dqsyntax only) indicates that the
1565 * quote character itself is not special (used parsing here docs and similar)
1566 *
1567 * The result is the type of the next token (its value, when there is one,
1568 * is saved in the relevant global var - must fix that someday!) which is
1569 * also saved for re-reading ("lasttoken").
1570 *
1571 * Overall, this routine does far more parsing than it is supposed to.
1572 * That will also need fixing, someday...
1573 */
1574 STATIC int
1575 readtoken1(int firstc, char const *syn, int magicq)
1576 {
1577 int c;
1578 char * out;
1579 int len;
1580 struct nodelist *bqlist;
1581 int quotef;
1582 VSS static_stack;
1583 VSS *stack = &static_stack;
1584
1585 stack->prev = NULL;
1586 stack->cur = 0;
1587
1588 syntax = syn;
1589
1590 startlinno = plinno;
1591 varnest = 0;
1592 quoted = 0;
1593 if (syntax == DQSYNTAX)
1594 SETDBLQUOTE();
1595 quotef = 0;
1596 bqlist = NULL;
1597 arinest = 0;
1598 parenlevel = 0;
1599 elided_nl = 0;
1600
1601 STARTSTACKSTR(out);
1602
1603 for (c = firstc ;; c = pgetc_macro()) { /* until of token */
1604 if (syntax == ARISYNTAX)
1605 out = insert_elided_nl(out);
1606 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1607 switch (syntax[c]) {
1608 case CNL: /* '\n' */
1609 if (syntax == BASESYNTAX)
1610 break; /* exit loop */
1611 USTPUTC(c, out);
1612 plinno++;
1613 if (doprompt)
1614 setprompt(2);
1615 else
1616 setprompt(0);
1617 continue;
1618
1619 case CWORD:
1620 USTPUTC(c, out);
1621 continue;
1622 case CCTL:
1623 if (!magicq || ISDBLQUOTE())
1624 USTPUTC(CTLESC, out);
1625 USTPUTC(c, out);
1626 continue;
1627 case CBACK: /* backslash */
1628 c = pgetc();
1629 if (c == PEOF) {
1630 USTPUTC('\\', out);
1631 pungetc();
1632 continue;
1633 }
1634 if (c == '\n') {
1635 plinno++;
1636 elided_nl++;
1637 if (doprompt)
1638 setprompt(2);
1639 else
1640 setprompt(0);
1641 continue;
1642 }
1643 quotef = 1; /* current token is quoted */
1644 if (ISDBLQUOTE() && c != '\\' && c != '`' &&
1645 c != '$' && (c != '"' || magicq))
1646 USTPUTC('\\', out);
1647 if (SQSYNTAX[c] == CCTL)
1648 USTPUTC(CTLESC, out);
1649 else if (!magicq) {
1650 USTPUTC(CTLQUOTEMARK, out);
1651 USTPUTC(c, out);
1652 if (varnest != 0)
1653 USTPUTC(CTLQUOTEEND, out);
1654 continue;
1655 }
1656 USTPUTC(c, out);
1657 continue;
1658 case CSQUOTE:
1659 if (syntax != SQSYNTAX) {
1660 if (!magicq)
1661 USTPUTC(CTLQUOTEMARK, out);
1662 quotef = 1;
1663 TS_PUSH();
1664 syntax = SQSYNTAX;
1665 quoted = SQ;
1666 continue;
1667 }
1668 if (magicq && arinest == 0 && varnest == 0) {
1669 /* Ignore inside quoted here document */
1670 USTPUTC(c, out);
1671 continue;
1672 }
1673 /* End of single quotes... */
1674 TS_POP();
1675 if (syntax == BASESYNTAX && varnest != 0)
1676 USTPUTC(CTLQUOTEEND, out);
1677 continue;
1678 case CDQUOTE:
1679 if (magicq && arinest == 0 && varnest == 0) {
1680 /* Ignore inside here document */
1681 USTPUTC(c, out);
1682 continue;
1683 }
1684 quotef = 1;
1685 if (arinest) {
1686 if (ISDBLQUOTE()) {
1687 TS_POP();
1688 } else {
1689 TS_PUSH();
1690 syntax = DQSYNTAX;
1691 SETDBLQUOTE();
1692 USTPUTC(CTLQUOTEMARK, out);
1693 }
1694 continue;
1695 }
1696 if (magicq)
1697 continue;
1698 if (ISDBLQUOTE()) {
1699 TS_POP();
1700 if (varnest != 0)
1701 USTPUTC(CTLQUOTEEND, out);
1702 } else {
1703 TS_PUSH();
1704 syntax = DQSYNTAX;
1705 SETDBLQUOTE();
1706 USTPUTC(CTLQUOTEMARK, out);
1707 }
1708 continue;
1709 case CVAR: /* '$' */
1710 out = insert_elided_nl(out);
1711 PARSESUB(); /* parse substitution */
1712 continue;
1713 case CENDVAR: /* CLOSEBRACE */
1714 if (varnest > 0 && !ISDBLQUOTE()) {
1715 TS_POP();
1716 USTPUTC(CTLENDVAR, out);
1717 } else {
1718 USTPUTC(c, out);
1719 }
1720 out = insert_elided_nl(out);
1721 continue;
1722 case CLP: /* '(' in arithmetic */
1723 parenlevel++;
1724 USTPUTC(c, out);
1725 continue;;
1726 case CRP: /* ')' in arithmetic */
1727 if (parenlevel > 0) {
1728 USTPUTC(c, out);
1729 --parenlevel;
1730 } else {
1731 if (pgetc_linecont() == ')') {
1732 out = insert_elided_nl(out);
1733 if (--arinest == 0) {
1734 TS_POP();
1735 USTPUTC(CTLENDARI, out);
1736 } else
1737 USTPUTC(')', out);
1738 } else {
1739 /*
1740 * unbalanced parens
1741 * (don't 2nd guess - no error)
1742 */
1743 pungetc();
1744 USTPUTC(')', out);
1745 }
1746 }
1747 continue;
1748 case CBQUOTE: /* '`' */
1749 out = parsebackq(stack, out, &bqlist, 1);
1750 continue;
1751 case CEOF: /* --> c == PEOF */
1752 break; /* will exit loop */
1753 default:
1754 if (varnest == 0 && !ISDBLQUOTE())
1755 break; /* exit loop */
1756 USTPUTC(c, out);
1757 continue;
1758 }
1759 break; /* break from switch -> break from for loop too */
1760 }
1761
1762 if (syntax == ARISYNTAX) {
1763 cleanup_state_stack(stack);
1764 synerror("Missing '))'");
1765 }
1766 if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
1767 cleanup_state_stack(stack);
1768 synerror("Unterminated quoted string");
1769 }
1770 if (varnest != 0) {
1771 cleanup_state_stack(stack);
1772 startlinno = plinno;
1773 /* { */
1774 synerror("Missing '}'");
1775 }
1776
1777 USTPUTC('\0', out);
1778 len = out - stackblock();
1779 out = stackblock();
1780
1781 if (!magicq) {
1782 if ((c == '<' || c == '>')
1783 && quotef == 0 && (*out == '\0' || is_number(out))) {
1784 parseredir(out, c);
1785 cleanup_state_stack(stack);
1786 return lasttoken = TREDIR;
1787 } else {
1788 pungetc();
1789 }
1790 }
1791
1792 quoteflag = quotef;
1793 backquotelist = bqlist;
1794 grabstackblock(len);
1795 wordtext = out;
1796 cleanup_state_stack(stack);
1797 return lasttoken = TWORD;
1798 /* end of readtoken routine */
1799
1800
1801 /*
1802 * Parse a substitution. At this point, we have read the dollar sign
1803 * and nothing else.
1804 */
1805
1806 parsesub: {
1807 int subtype;
1808 int typeloc;
1809 int flags;
1810 char *p;
1811 static const char types[] = "}-+?=";
1812
1813 c = pgetc_linecont();
1814 if (c != '('/*)*/ && c != OPENBRACE && !is_name(c) && !is_special(c)) {
1815 USTPUTC('$', out);
1816 pungetc();
1817 } else if (c == '('/*)*/) { /* $(command) or $((arith)) */
1818 if (pgetc_linecont() == '(' /*')'*/ ) {
1819 out = insert_elided_nl(out);
1820 PARSEARITH();
1821 } else {
1822 out = insert_elided_nl(out);
1823 pungetc();
1824 out = parsebackq(stack, out, &bqlist, 0);
1825 }
1826 } else {
1827 USTPUTC(CTLVAR, out);
1828 typeloc = out - stackblock();
1829 USTPUTC(VSNORMAL, out);
1830 subtype = VSNORMAL;
1831 flags = 0;
1832 if (c == OPENBRACE) {
1833 c = pgetc_linecont();
1834 if (c == '#') {
1835 if ((c = pgetc_linecont()) == CLOSEBRACE)
1836 c = '#';
1837 else if (is_name(c) || isdigit(c))
1838 subtype = VSLENGTH;
1839 else if (is_special(c)) {
1840 /*
1841 * ${#} is $# - the number of sh params
1842 * ${##} is the length of ${#}
1843 * ${###} is ${#} with as much nothing
1844 * as possible removed from start
1845 * ${##1} is ${#} with leading 1 gone
1846 * ${##\#} is ${#} with leading # gone
1847 *
1848 * this stuff is UGLY!
1849 */
1850 if (pgetc_linecont() == CLOSEBRACE) {
1851 pungetc();
1852 subtype = VSLENGTH;
1853 } else {
1854 static char cbuf[2];
1855
1856 pungetc(); /* would like 2 */
1857 cbuf[0] = c; /* so ... */
1858 cbuf[1] = '\0';
1859 pushstring(cbuf, 1, NULL);
1860 c = '#'; /* ${#:...} */
1861 subtype = 0; /* .. or similar */
1862 }
1863 } else {
1864 pungetc();
1865 c = '#';
1866 subtype = 0;
1867 }
1868 }
1869 else
1870 subtype = 0;
1871 }
1872 if (is_name(c)) {
1873 p = out;
1874 do {
1875 STPUTC(c, out);
1876 c = pgetc_linecont();
1877 } while (is_in_name(c));
1878 #if 0
1879 if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
1880 int i;
1881 int linno;
1882 char buf[10];
1883
1884 /*
1885 * The "LINENO hack"
1886 *
1887 * Replace the variable name with the
1888 * current line number.
1889 */
1890 linno = plinno;
1891 if (funclinno != 0)
1892 linno -= funclinno - 1;
1893 snprintf(buf, sizeof(buf), "%d", linno);
1894 STADJUST(-6, out);
1895 for (i = 0; buf[i] != '\0'; i++)
1896 STPUTC(buf[i], out);
1897 flags |= VSLINENO;
1898 }
1899 #endif
1900 } else if (is_digit(c)) {
1901 do {
1902 STPUTC(c, out);
1903 c = pgetc_linecont();
1904 } while (subtype != VSNORMAL && is_digit(c));
1905 }
1906 else if (is_special(c)) {
1907 USTPUTC(c, out);
1908 c = pgetc_linecont();
1909 }
1910 else {
1911 badsub:
1912 cleanup_state_stack(stack);
1913 synerror("Bad substitution");
1914 }
1915
1916 STPUTC('=', out);
1917 if (subtype == 0) {
1918 switch (c) {
1919 case ':':
1920 flags |= VSNUL;
1921 c = pgetc_linecont();
1922 /*FALLTHROUGH*/
1923 default:
1924 p = strchr(types, c);
1925 if (p == NULL)
1926 goto badsub;
1927 subtype = p - types + VSNORMAL;
1928 break;
1929 case '%':
1930 case '#':
1931 {
1932 int cc = c;
1933 subtype = c == '#' ? VSTRIMLEFT :
1934 VSTRIMRIGHT;
1935 c = pgetc_linecont();
1936 if (c == cc)
1937 subtype++;
1938 else
1939 pungetc();
1940 break;
1941 }
1942 }
1943 } else {
1944 if (subtype == VSLENGTH && c != /*{*/ '}')
1945 synerror("no modifiers allowed with ${#var}");
1946 pungetc();
1947 }
1948 if (ISDBLQUOTE() || arinest)
1949 flags |= VSQUOTE;
1950 if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
1951 flags |= VSPATQ;
1952 *(stackblock() + typeloc) = subtype | flags;
1953 if (subtype != VSNORMAL) {
1954 TS_PUSH();
1955 varnest++;
1956 arinest = 0;
1957 if (subtype > VSASSIGN) { /* # ## % %% */
1958 syntax = BASESYNTAX;
1959 CLRDBLQUOTE();
1960 }
1961 }
1962 }
1963 goto parsesub_return;
1964 }
1965
1966
1967 /*
1968 * Parse an arithmetic expansion (indicate start of one and set state)
1969 */
1970 parsearith: {
1971
1972 #if 0
1973 if (syntax == ARISYNTAX) {
1974 /*
1975 * we collapse embedded arithmetic expansion to
1976 * parentheses, which should be equivalent
1977 *
1978 * XXX It isn't, must fix, soonish...
1979 */
1980 USTPUTC('(', out);
1981 USTPUTC('(', out);
1982 /*
1983 * Need 2 of them because there will (should be)
1984 * two closing ))'s to follow later.
1985 */
1986 parenlevel += 2;
1987 } else
1988 #endif
1989 {
1990 USTPUTC(CTLARI, out);
1991 if (ISDBLQUOTE())
1992 USTPUTC('"',out);
1993 else
1994 USTPUTC(' ',out);
1995
1996 TS_PUSH();
1997 syntax = ARISYNTAX;
1998 arinest = 1;
1999 varnest = 0;
2000 }
2001 goto parsearith_return;
2002 }
2003
2004 } /* end of readtoken */
2005
2006
2007
2008
2009 #ifdef mkinit
2010 RESET {
2011 tokpushback = 0;
2012 checkkwd = 0;
2013 }
2014 #endif
2015
2016 /*
2017 * Returns true if the text contains nothing to expand (no dollar signs
2018 * or backquotes).
2019 */
2020
2021 STATIC int
2022 noexpand(char *text)
2023 {
2024 char *p;
2025 char c;
2026
2027 p = text;
2028 while ((c = *p++) != '\0') {
2029 if (c == CTLQUOTEMARK)
2030 continue;
2031 if (c == CTLESC)
2032 p++;
2033 else if (BASESYNTAX[(int)c] == CCTL)
2034 return 0;
2035 }
2036 return 1;
2037 }
2038
2039
2040 /*
2041 * Return true if the argument is a legal variable name (a letter or
2042 * underscore followed by zero or more letters, underscores, and digits).
2043 */
2044
2045 int
2046 goodname(char *name)
2047 {
2048 char *p;
2049
2050 p = name;
2051 if (! is_name(*p))
2052 return 0;
2053 while (*++p) {
2054 if (! is_in_name(*p))
2055 return 0;
2056 }
2057 return 1;
2058 }
2059
2060
2061 /*
2062 * Called when an unexpected token is read during the parse. The argument
2063 * is the token that is expected, or -1 if more than one type of token can
2064 * occur at this point.
2065 */
2066
2067 STATIC void
2068 synexpect(int token, const char *text)
2069 {
2070 char msg[64];
2071 char *p;
2072
2073 if (lasttoken == TWORD) {
2074 size_t len = strlen(wordtext);
2075
2076 if (len <= 13)
2077 fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
2078 else
2079 fmtstr(msg, 34,
2080 "Word \"%.10s...\" unexpected", wordtext);
2081 } else
2082 fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
2083
2084 p = strchr(msg, '\0');
2085 if (text)
2086 fmtstr(p, 30, " (expecting \"%.10s\")", text);
2087 else if (token >= 0)
2088 fmtstr(p, 30, " (expecting %s)", tokname[token]);
2089
2090 synerror(msg);
2091 /* NOTREACHED */
2092 }
2093
2094
2095 STATIC void
2096 synerror(const char *msg)
2097 {
2098 error("%d: Syntax error: %s", startlinno, msg);
2099 /* NOTREACHED */
2100 }
2101
2102 STATIC void
2103 setprompt(int which)
2104 {
2105 whichprompt = which;
2106
2107 #ifndef SMALL
2108 if (!el)
2109 #endif
2110 out2str(getprompt(NULL));
2111 }
2112
2113 /*
2114 * handle getting the next character, while ignoring \ \n
2115 * (which is a little tricky as we only have one char of pushback
2116 * and we need that one elsewhere).
2117 */
2118 STATIC int
2119 pgetc_linecont(void)
2120 {
2121 int c;
2122
2123 while ((c = pgetc_macro()) == '\\') {
2124 c = pgetc();
2125 if (c == '\n') {
2126 plinno++;
2127 elided_nl++;
2128 if (doprompt)
2129 setprompt(2);
2130 else
2131 setprompt(0);
2132 } else {
2133 pungetc();
2134 /* Allow the backslash to be pushed back. */
2135 pushstring("\\", 1, NULL);
2136 return (pgetc());
2137 }
2138 }
2139 return (c);
2140 }
2141
2142 /*
2143 * called by editline -- any expansions to the prompt
2144 * should be added here.
2145 */
2146 const char *
2147 getprompt(void *unused)
2148 {
2149 switch (whichprompt) {
2150 case 0:
2151 return "";
2152 case 1:
2153 return ps1val();
2154 case 2:
2155 return ps2val();
2156 default:
2157 return "<internal prompt error>";
2158 }
2159 }
2160