2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)parser.c 8.7 (Berkeley) 5/16/95
37 * $FreeBSD: src/bin/sh/parser.c,v 1.115 2011/06/18 23:58:59 jilles Exp $
47 #include "expand.h" /* defines rmescapes() */
59 #include "exec.h" /* to check for special builtins */
61 #include "myhistedit.h"
65 * Shell command parser.
71 /* values of checkkwd variable */
76 /* values returned by readtoken */
82 struct heredoc *next; /* next here document in list */
83 union node *here; /* redirection node */
84 char *eofmark; /* string indicating end of input */
85 int striptabs; /* if set, strip leading tabs */
89 struct parser_temp *next;
94 static struct heredoc *heredoclist; /* list of here documents to read */
95 static int doprompt; /* if set, prompt the user */
96 static int needprompt; /* true if interactive and at start of line */
97 static int lasttoken; /* last token read */
98 MKINIT int tokpushback; /* last token pushed back */
99 static char *wordtext; /* text of last word returned by readtoken */
100 MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
101 static struct nodelist *backquotelist;
102 static union node *redirnode;
103 static struct heredoc *heredoc;
104 static int quoteflag; /* set if (part of) last token was quoted */
105 static int startlinno; /* line # where last token started */
106 static int funclinno; /* line # where the current function started */
107 static struct parser_temp *parser_temp;
110 static union node *list(int, int);
111 static union node *andor(void);
112 static union node *pipeline(void);
113 static union node *command(void);
114 static union node *simplecmd(union node **, union node *);
115 static union node *makename(void);
116 static void parsefname(void);
117 static void parseheredoc(void);
118 static int peektoken(void);
119 static int readtoken(void);
120 static int xxreadtoken(void);
121 static int readtoken1(int, char const *, char *, int);
122 static int noexpand(char *);
123 static void synexpect(int) __dead2;
124 static void synerror(const char *) __dead2;
125 static void setprompt(int);
129 parser_temp_alloc(size_t len)
131 struct parser_temp *t;
134 t = ckmalloc(sizeof(*t));
136 t->next = parser_temp;
138 t->data = ckmalloc(len);
145 parser_temp_realloc(void *ptr, size_t len)
147 struct parser_temp *t;
152 error("bug: parser_temp_realloc misused");
153 t->data = ckrealloc(t->data, len);
160 parser_temp_free_upto(void *ptr)
162 struct parser_temp *t;
166 while (parser_temp != NULL && !done) {
168 parser_temp = t->next;
169 done = t->data == ptr;
175 error("bug: parser_temp_free_upto misused");
180 parser_temp_free_all(void)
182 struct parser_temp *t;
185 while (parser_temp != NULL) {
187 parser_temp = t->next;
196 * Read and parse a command. Returns NEOF on end of file. (NULL is a
197 * valid parse tree indicating a blank line.)
201 parsecmd(int interact)
205 /* This assumes the parser is not re-entered,
206 * which could happen if we add command substitution on PS1/PS2.
208 parser_temp_free_all();
229 list(int nlflag, int erflag)
231 union node *ntop, *n1, *n2, *n3;
234 checkkwd = CHKNL | CHKKWD | CHKALIAS;
235 if (!nlflag && !erflag && tokendlist[peektoken()])
241 if (tok == TBACKGND) {
242 if (n2->type == NPIPE) {
243 n2->npipe.backgnd = 1;
244 } else if (n2->type == NREDIR) {
247 n3 = (union node *)stalloc(sizeof (struct nredir));
250 n3->nredir.redirect = NULL;
256 else if (n1 == NULL) {
257 n1 = (union node *)stalloc(sizeof (struct nbinary));
259 n1->nbinary.ch1 = ntop;
260 n1->nbinary.ch2 = n2;
264 n3 = (union node *)stalloc(sizeof (struct nbinary));
266 n3->nbinary.ch1 = n1->nbinary.ch2;
267 n3->nbinary.ch2 = n2;
268 n1->nbinary.ch2 = n3;
281 } else if (tok == TEOF && nlflag) {
287 checkkwd = CHKNL | CHKKWD | CHKALIAS;
288 if (!nlflag && !erflag && tokendlist[peektoken()])
295 pungetc(); /* push back EOF on input */
298 if (nlflag || erflag)
311 union node *n1, *n2, *n3;
316 if ((t = readtoken()) == TAND) {
318 } else if (t == TOR) {
325 n3 = (union node *)stalloc(sizeof (struct nbinary));
327 n3->nbinary.ch1 = n1;
328 n3->nbinary.ch2 = n2;
338 union node *n1, *n2, *pipenode;
339 struct nodelist *lp, *prev;
343 checkkwd = CHKNL | CHKKWD | CHKALIAS;
344 TRACE(("pipeline: entered\n"));
345 while (readtoken() == TNOT)
349 if (readtoken() == TPIPE) {
350 pipenode = (union node *)stalloc(sizeof (struct npipe));
351 pipenode->type = NPIPE;
352 pipenode->npipe.backgnd = 0;
353 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
354 pipenode->npipe.cmdlist = lp;
358 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
359 checkkwd = CHKNL | CHKKWD | CHKALIAS;
367 } while (readtoken() == TPIPE);
373 n2 = (union node *)stalloc(sizeof (struct nnot));
387 union node *ap, **app;
388 union node *cp, **cpp;
389 union node *redir, **rpp;
393 checkkwd = CHKNL | CHKKWD | CHKALIAS;
399 /* Check for redirection which may precede command */
400 while (readtoken() == TREDIR) {
401 *rpp = n2 = redirnode;
402 rpp = &n2->nfile.next;
407 switch (readtoken()) {
409 n1 = (union node *)stalloc(sizeof (struct nif));
411 if ((n1->nif.test = list(0, 0)) == NULL)
413 if (readtoken() != TTHEN)
415 n1->nif.ifpart = list(0, 0);
417 while (readtoken() == TELIF) {
418 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
419 n2 = n2->nif.elsepart;
421 if ((n2->nif.test = list(0, 0)) == NULL)
423 if (readtoken() != TTHEN)
425 n2->nif.ifpart = list(0, 0);
427 if (lasttoken == TELSE)
428 n2->nif.elsepart = list(0, 0);
430 n2->nif.elsepart = NULL;
433 if (readtoken() != TFI)
435 checkkwd = CHKKWD | CHKALIAS;
440 n1 = (union node *)stalloc(sizeof (struct nbinary));
441 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
442 if ((n1->nbinary.ch1 = list(0, 0)) == NULL)
444 if ((got=readtoken()) != TDO) {
445 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
448 n1->nbinary.ch2 = list(0, 0);
449 if (readtoken() != TDONE)
451 checkkwd = CHKKWD | CHKALIAS;
455 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
456 synerror("Bad for loop variable");
457 n1 = (union node *)stalloc(sizeof (struct nfor));
459 n1->nfor.var = wordtext;
460 while (readtoken() == TNL)
462 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
464 while (readtoken() == TWORD) {
465 n2 = (union node *)stalloc(sizeof (struct narg));
467 n2->narg.text = wordtext;
468 n2->narg.backquote = backquotelist;
470 app = &n2->narg.next;
474 if (lasttoken != TNL && lasttoken != TSEMI)
477 static char argvars[5] = {
478 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
480 n2 = (union node *)stalloc(sizeof (struct narg));
482 n2->narg.text = argvars;
483 n2->narg.backquote = NULL;
484 n2->narg.next = NULL;
487 * Newline or semicolon here is optional (but note
488 * that the original Bourne shell only allowed NL).
490 if (lasttoken != TNL && lasttoken != TSEMI)
493 checkkwd = CHKNL | CHKKWD | CHKALIAS;
494 if ((t = readtoken()) == TDO)
496 else if (t == TBEGIN)
500 n1->nfor.body = list(0, 0);
501 if (readtoken() != t)
503 checkkwd = CHKKWD | CHKALIAS;
506 n1 = (union node *)stalloc(sizeof (struct ncase));
508 if (readtoken() != TWORD)
510 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
512 n2->narg.text = wordtext;
513 n2->narg.backquote = backquotelist;
514 n2->narg.next = NULL;
515 while (readtoken() == TNL);
516 if (lasttoken != TWORD || ! equal(wordtext, "in"))
517 synerror("expecting \"in\"");
518 cpp = &n1->ncase.cases;
519 checkkwd = CHKNL | CHKKWD, readtoken();
520 while (lasttoken != TESAC) {
521 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
523 app = &cp->nclist.pattern;
524 if (lasttoken == TLP)
527 *app = ap = (union node *)stalloc(sizeof (struct narg));
529 ap->narg.text = wordtext;
530 ap->narg.backquote = backquotelist;
531 checkkwd = CHKNL | CHKKWD;
532 if (readtoken() != TPIPE)
534 app = &ap->narg.next;
537 ap->narg.next = NULL;
538 if (lasttoken != TRP)
540 cp->nclist.body = list(0, 0);
542 checkkwd = CHKNL | CHKKWD | CHKALIAS;
543 if ((t = readtoken()) != TESAC) {
546 else if (t == TFALLTHRU)
547 cp->type = NCLISTFALLTHRU;
550 checkkwd = CHKNL | CHKKWD, readtoken();
552 cpp = &cp->nclist.next;
555 checkkwd = CHKKWD | CHKALIAS;
558 n1 = (union node *)stalloc(sizeof (struct nredir));
559 n1->type = NSUBSHELL;
560 n1->nredir.n = list(0, 0);
561 n1->nredir.redirect = NULL;
562 if (readtoken() != TRP)
564 checkkwd = CHKKWD | CHKALIAS;
569 if (readtoken() != TEND)
571 checkkwd = CHKKWD | CHKALIAS;
573 /* Handle an empty command like other simple commands. */
579 * An empty command before a ; doesn't make much sense, and
580 * should certainly be disallowed in the case of `if ;'.
589 n1 = simplecmd(rpp, redir);
595 /* Now check for redirection which may follow command */
596 while (readtoken() == TREDIR) {
597 *rpp = n2 = redirnode;
598 rpp = &n2->nfile.next;
605 n2 = (union node *)stalloc(sizeof (struct nredir));
610 n1->nredir.redirect = redir;
618 simplecmd(union node **rpp, union node *redir)
620 union node *args, **app;
621 union node **orig_rpp = rpp;
622 union node *n = NULL;
626 /* If we don't have any redirections already, then we must reset */
627 /* rpp to be the address of the local redir variable. */
634 * We save the incoming value, because we need this for shell
635 * functions. There can not be a redirect or an argument between
636 * the function name and the open parenthesis.
640 savecheckkwd = CHKALIAS;
643 checkkwd = savecheckkwd;
644 if (readtoken() == TWORD) {
645 n = (union node *)stalloc(sizeof (struct narg));
647 n->narg.text = wordtext;
648 n->narg.backquote = backquotelist;
651 if (savecheckkwd != 0 && !isassignment(wordtext))
653 } else if (lasttoken == TREDIR) {
654 *rpp = n = redirnode;
655 rpp = &n->nfile.next;
656 parsefname(); /* read name of redirection file */
657 } else if (lasttoken == TLP && app == &args->narg.next
658 && rpp == orig_rpp) {
659 /* We have a function */
660 if (readtoken() != TRP)
664 * - Require plain text.
665 * - Functions with '/' cannot be called.
667 * - Reject ksh extended glob patterns.
669 if (!noexpand(n->narg.text) || quoteflag ||
670 strchr(n->narg.text, '/') ||
672 n->narg.text[strlen(n->narg.text) - 1]))
673 synerror("Bad function name");
674 rmescapes(n->narg.text);
675 if (find_builtin(n->narg.text, &special) >= 0 &&
677 synerror("Cannot override a special builtin with a function");
679 n->narg.next = command();
689 n = (union node *)stalloc(sizeof (struct ncmd));
692 n->ncmd.redirect = redir;
701 n = (union node *)stalloc(sizeof (struct narg));
704 n->narg.text = wordtext;
705 n->narg.backquote = backquotelist;
710 fixredir(union node *n, const char *text, int err)
712 TRACE(("Fix redir %s %d\n", text, err));
714 n->ndup.vname = NULL;
716 if (is_digit(text[0]) && text[1] == '\0')
717 n->ndup.dupfd = digit_val(text[0]);
718 else if (text[0] == '-' && text[1] == '\0')
723 synerror("Bad fd number");
725 n->ndup.vname = makename();
733 union node *n = redirnode;
735 if (readtoken() != TWORD)
737 if (n->type == NHERE) {
738 struct heredoc *here = heredoc;
744 TRACE(("Here document %d\n", n->type));
745 if (here->striptabs) {
746 while (*wordtext == '\t')
749 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
750 synerror("Illegal eof marker for << redirection");
752 here->eofmark = wordtext;
754 if (heredoclist == NULL)
757 for (p = heredoclist ; p->next ; p = p->next);
760 } else if (n->type == NTOFD || n->type == NFROMFD) {
761 fixredir(n, wordtext, 0);
763 n->nfile.fname = makename();
769 * Input any here documents.
775 struct heredoc *here;
778 while (heredoclist) {
780 heredoclist = here->next;
785 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
786 here->eofmark, here->striptabs);
787 n = (union node *)stalloc(sizeof (struct narg));
790 n->narg.text = wordtext;
791 n->narg.backquote = backquotelist;
792 here->here->nhere.doc = n;
812 int alreadyseen = tokpushback;
821 if (checkkwd & CHKNL) {
829 * check for keywords and aliases
831 if (t == TWORD && !quoteflag)
833 const char * const *pp;
835 if (checkkwd & CHKKWD)
836 for (pp = parsekwd; *pp; pp++) {
837 if (**pp == *wordtext && equal(*pp, wordtext))
839 lasttoken = t = pp - parsekwd + KWDOFFSET;
840 TRACE(("keyword %s recognized\n", tokname[t]));
844 if (checkkwd & CHKALIAS &&
845 (ap = lookupalias(wordtext, 1)) != NULL) {
846 pushstring(ap->val, strlen(ap->val), ap);
856 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
858 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
865 * Read the next input token.
866 * If the token is a word, we set backquotelist to the list of cmds in
867 * backquotes. We set quoteflag to true if any part of the word was
869 * If the token is TREDIR, then we set redirnode to a structure containing
871 * In all cases, the variable startlinno is set to the number of the line
872 * on which the token starts.
874 * [Change comment: here documents and internal procedures]
875 * [Readtoken shouldn't have any arguments. Perhaps we should make the
876 * word parsing code into a separate routine. In this case, readtoken
877 * doesn't need to have any internal procedures, but parseword does.
878 * We could also make parseoperator in essence the main routine, and
879 * have parseword (readtoken1?) handle both words and redirection.]
882 #define RETURN(token) return lasttoken = token
898 for (;;) { /* until token or start of word found */
904 while ((c = pgetc()) != '\n' && c != PEOF);
908 if (pgetc() == '\n') {
909 startlinno = ++plinno;
920 needprompt = doprompt;
951 return readtoken1(c, BASESYNTAX, NULL, 0);
956 #define MAXNEST_STATIC 8
959 const char *syntax; /* *SYNTAX */
960 int parenlevel; /* levels of parentheses in arithmetic */
961 enum tokenstate_category
964 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
965 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
972 * Called to parse command substitutions.
976 parsebackq(char *out, struct nodelist **pbqlist,
977 int oldstyle, int dblquote, int quoted)
979 struct nodelist **nlpp;
982 struct jmploc jmploc;
983 struct jmploc *const savehandler = handler;
986 const int bq_startlinno = plinno;
987 char *volatile ostr = NULL;
988 struct parsefile *const savetopfile = getcurrentfile();
989 struct heredoc *const saveheredoclist = heredoclist;
990 struct heredoc *here;
993 if (setjmp(jmploc.loc)) {
994 popfilesupto(savetopfile);
999 heredoclist = saveheredoclist;
1000 handler = savehandler;
1001 if (exception == EXERROR) {
1002 startlinno = bq_startlinno;
1003 synerror("Error in command substitution");
1005 longjmp(handler->loc, 1);
1008 savelen = out - stackblock();
1010 str = ckmalloc(savelen);
1011 memcpy(str, stackblock(), savelen);
1018 * We must read until the closing backquote, giving special
1019 * treatment to some slashes, and then push the string and
1020 * reread it as input, interpreting it normally.
1025 STARTSTACKSTR(oout);
1031 CHECKSTRSPACE(2, oout);
1032 switch (c = pgetc()) {
1037 if ((c = pgetc()) == '\n') {
1044 * If eating a newline, avoid putting
1045 * the newline into the new character
1046 * stream (via the USTPUTC after the
1051 if (c != '\\' && c != '`' && c != '$'
1052 && (!dblquote || c != '"'))
1053 USTPUTC('\\', oout);
1058 needprompt = doprompt;
1062 startlinno = plinno;
1063 synerror("EOF in backquote substitution");
1072 USTPUTC('\0', oout);
1073 olen = oout - stackblock();
1075 ostr = ckmalloc(olen);
1076 memcpy(ostr, stackblock(), olen);
1077 setinputstring(ostr, 1);
1082 nlpp = &(*nlpp)->next;
1083 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1084 (*nlpp)->next = NULL;
1087 saveprompt = doprompt;
1091 n = list(0, oldstyle);
1094 doprompt = saveprompt;
1096 if (readtoken() != TRP)
1103 * Start reading from old file again, ignoring any pushed back
1104 * tokens left from the backquote parsing
1110 CHECKSTRSPACE(savelen + 1, out);
1113 memcpy(out, str, savelen);
1114 STADJUST(savelen, out);
1122 here = saveheredoclist;
1124 while (here->next != NULL)
1126 here->next = heredoclist;
1127 heredoclist = saveheredoclist;
1129 handler = savehandler;
1132 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1134 USTPUTC(CTLBACKQ, out);
1140 * Called to parse a backslash escape sequence inside $'...'.
1141 * The backslash has already been read.
1144 readcstyleesc(char *out)
1151 synerror("Unterminated quoted string");
1164 case 'a': v = '\a'; break;
1165 case 'b': v = '\b'; break;
1166 case 'e': v = '\033'; break;
1167 case 'f': v = '\f'; break;
1168 case 'n': v = '\n'; break;
1169 case 'r': v = '\r'; break;
1170 case 't': v = '\t'; break;
1171 case 'v': v = '\v'; break;
1176 if (c >= '0' && c <= '9')
1177 v = (v << 4) + c - '0';
1178 else if (c >= 'A' && c <= 'F')
1179 v = (v << 4) + c - 'A' + 10;
1180 else if (c >= 'a' && c <= 'f')
1181 v = (v << 4) + c - 'a' + 10;
1187 case '0': case '1': case '2': case '3':
1188 case '4': case '5': case '6': case '7':
1191 if (c >= '0' && c <= '7') {
1195 if (c >= '0' && c <= '7') {
1205 if (c < 0x3f || c > 0x7a || c == 0x60)
1206 synerror("Bad escape sequence");
1207 if (c == '\\' && pgetc() != '\\')
1208 synerror("Bad escape sequence");
1216 n = c == 'U' ? 8 : 4;
1218 for (i = 0; i < n; i++) {
1220 if (c >= '0' && c <= '9')
1221 v = (v << 4) + c - '0';
1222 else if (c >= 'A' && c <= 'F')
1223 v = (v << 4) + c - 'A' + 10;
1224 else if (c >= 'a' && c <= 'f')
1225 v = (v << 4) + c - 'a' + 10;
1227 synerror("Bad escape sequence");
1229 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1230 synerror("Bad escape sequence");
1231 /* We really need iconv here. */
1232 if (initial_localeisutf8 && v > 127) {
1233 CHECKSTRSPACE(4, out);
1235 * We cannot use wctomb() as the locale may have
1239 USTPUTC(0xc0 | v >> 6, out);
1240 USTPUTC(0x80 | (v & 0x3f), out);
1242 } else if (v <= 0xffff) {
1243 USTPUTC(0xe0 | v >> 12, out);
1244 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1245 USTPUTC(0x80 | (v & 0x3f), out);
1247 } else if (v <= 0x10ffff) {
1248 USTPUTC(0xf0 | v >> 18, out);
1249 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1250 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1251 USTPUTC(0x80 | (v & 0x3f), out);
1259 synerror("Bad escape sequence");
1263 * We can't handle NUL bytes.
1264 * POSIX says we should skip till the closing quote.
1267 while ((c = pgetc()) != '\'') {
1271 synerror("Unterminated quoted string");
1276 if (SQSYNTAX[v] == CCTL)
1277 USTPUTC(CTLESC, out);
1284 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1285 * is not NULL, read a here document. In the latter case, eofmark is the
1286 * word which marks the end of the document and striptabs is true if
1287 * leading tabs should be stripped from the document. The argument firstc
1288 * is the first character of the input token or document.
1290 * Because C does not have internal subroutines, I have simulated them
1291 * using goto's to implement the subroutine linkage. The following macros
1292 * will run code that appears at the end of readtoken1.
1295 #define CHECKEND() {goto checkend; checkend_return:;}
1296 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1297 #define PARSESUB() {goto parsesub; parsesub_return:;}
1298 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1301 readtoken1(int firstc, char const *initialsyntax, char *eofmark, int striptabs)
1304 char * volatile out;
1306 char line[EOFMARKLEN + 1];
1307 struct nodelist *bqlist;
1308 volatile int quotef;
1312 struct tokenstate state_static[MAXNEST_STATIC];
1313 int maxnest = MAXNEST_STATIC;
1314 struct tokenstate *state = state_static;
1317 startlinno = plinno;
1322 state[level].syntax = initialsyntax;
1323 state[level].parenlevel = 0;
1324 state[level].category = TSTATE_TOP;
1327 loop: { /* for each line, until end of word */
1328 CHECKEND(); /* set c to PEOF if at end of here document */
1329 for (;;) { /* until end of line or end of word */
1330 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1332 synentry = state[level].syntax[c];
1335 case CNL: /* '\n' */
1336 if (state[level].syntax == BASESYNTAX)
1337 goto endword; /* exit outer loop */
1345 goto loop; /* continue outer loop */
1348 out = readcstyleesc(out);
1356 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1357 USTPUTC(CTLESC, out);
1360 case CBACK: /* backslash */
1365 } else if (c == '\n') {
1372 if (state[level].syntax == DQSYNTAX &&
1373 c != '\\' && c != '`' && c != '$' &&
1374 (c != '"' || (eofmark != NULL &&
1375 newvarnest == 0)) &&
1376 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1378 if ((eofmark == NULL ||
1380 state[level].syntax == BASESYNTAX)
1381 USTPUTC(CTLQUOTEMARK, out);
1382 if (SQSYNTAX[c] == CCTL)
1383 USTPUTC(CTLESC, out);
1385 if ((eofmark == NULL ||
1387 state[level].syntax == BASESYNTAX &&
1388 state[level].category == TSTATE_VAR_OLD)
1389 USTPUTC(CTLQUOTEEND, out);
1394 USTPUTC(CTLQUOTEMARK, out);
1395 state[level].syntax = SQSYNTAX;
1399 USTPUTC(CTLQUOTEMARK, out);
1400 state[level].syntax = DQSYNTAX;
1403 if (eofmark != NULL && newvarnest == 0)
1406 if (state[level].category == TSTATE_VAR_OLD)
1407 USTPUTC(CTLQUOTEEND, out);
1408 state[level].syntax = BASESYNTAX;
1412 case CVAR: /* '$' */
1413 PARSESUB(); /* parse substitution */
1415 case CENDVAR: /* '}' */
1417 ((state[level].category == TSTATE_VAR_OLD &&
1418 state[level].syntax ==
1419 state[level - 1].syntax) ||
1420 (state[level].category == TSTATE_VAR_NEW &&
1421 state[level].syntax == BASESYNTAX))) {
1422 if (state[level].category == TSTATE_VAR_NEW)
1425 USTPUTC(CTLENDVAR, out);
1430 case CLP: /* '(' in arithmetic */
1431 state[level].parenlevel++;
1434 case CRP: /* ')' in arithmetic */
1435 if (state[level].parenlevel > 0) {
1437 --state[level].parenlevel;
1439 if (pgetc() == ')') {
1441 state[level].category == TSTATE_ARITH) {
1443 USTPUTC(CTLENDARI, out);
1449 * (don't 2nd guess - no error)
1456 case CBQUOTE: /* '`' */
1457 out = parsebackq(out, &bqlist, 1,
1458 state[level].syntax == DQSYNTAX &&
1459 (eofmark == NULL || newvarnest > 0),
1460 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1463 goto endword; /* exit outer loop */
1468 goto endword; /* exit outer loop */
1475 if (state[level].syntax == ARISYNTAX)
1476 synerror("Missing '))'");
1477 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1478 synerror("Unterminated quoted string");
1479 if (state[level].category == TSTATE_VAR_OLD ||
1480 state[level].category == TSTATE_VAR_NEW) {
1481 startlinno = plinno;
1482 synerror("Missing '}'");
1484 if (state != state_static)
1485 parser_temp_free_upto(state);
1487 len = out - stackblock();
1489 if (eofmark == NULL) {
1490 if ((c == '>' || c == '<')
1493 && (*out == '\0' || is_digit(*out))) {
1495 return lasttoken = TREDIR;
1501 backquotelist = bqlist;
1502 grabstackblock(len);
1504 return lasttoken = TWORD;
1505 /* end of readtoken routine */
1509 * Check to see whether we are at the end of the here document. When this
1510 * is called, c is set to the first character of the next input line. If
1511 * we are at the end of the here document, this routine sets the c to PEOF.
1520 if (c == *eofmark) {
1521 if (pfgets(line, sizeof line) != NULL) {
1525 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1526 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1530 needprompt = doprompt;
1533 pushstring(line, strlen(line), NULL);
1538 goto checkend_return;
1543 * Parse a redirection operator. The variable "out" points to a string
1544 * specifying the fd to be redirected. The variable "c" contains the
1545 * first character of the redirection operator.
1552 np = (union node *)stalloc(sizeof (struct nfile));
1561 np->type = NCLOBBER;
1566 } else { /* c == '<' */
1570 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1571 np = (union node *)stalloc(sizeof (struct nhere));
1575 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1577 if ((c = pgetc()) == '-') {
1578 heredoc->striptabs = 1;
1580 heredoc->striptabs = 0;
1583 } else if (c == '&')
1593 np->nfile.fd = digit_val(fd);
1595 goto parseredir_return;
1600 * Parse a substitution. At this point, we have read the dollar sign
1610 static const char types[] = "}-+?=";
1611 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1617 if (c == '(') { /* $(command) or $((arith)) */
1618 if (pgetc() == '(') {
1622 out = parsebackq(out, &bqlist, 0,
1623 state[level].syntax == DQSYNTAX &&
1624 (eofmark == NULL || newvarnest > 0),
1625 state[level].syntax == DQSYNTAX ||
1626 state[level].syntax == ARISYNTAX);
1628 } else if (c == '{' || is_name(c) || is_special(c)) {
1629 USTPUTC(CTLVAR, out);
1630 typeloc = out - stackblock();
1631 USTPUTC(VSNORMAL, out);
1640 if (!is_eof(c) && is_name(c)) {
1646 } while (!is_eof(c) && is_in_name(c));
1648 strncmp(out - length, "LINENO", length) == 0) {
1649 /* Replace the variable name with the
1650 * current line number. */
1653 linno -= funclinno - 1;
1654 snprintf(buf, sizeof(buf), "%d", linno);
1659 } else if (is_digit(c)) {
1660 if (bracketed_name) {
1664 } while (is_digit(c));
1669 } else if (is_special(c)) {
1672 if (subtype == 0 && c1 == '#') {
1674 if (strchr(types, c) == NULL && c != ':' &&
1675 c != '#' && c != '%')
1679 if (c1 != '}' && c == '}') {
1694 else if (c == '\n' || c == PEOF)
1695 synerror("Unexpected end of line in substitution");
1706 p = strchr(types, c);
1708 if (c == '\n' || c == PEOF)
1709 synerror("Unexpected end of line in substitution");
1715 subtype = p - types + VSNORMAL;
1721 subtype = c == '#' ? VSTRIMLEFT :
1731 } else if (subtype != VSERROR) {
1732 if (subtype == VSLENGTH && c != '}')
1737 if (state[level].syntax == DQSYNTAX ||
1738 state[level].syntax == ARISYNTAX)
1740 *(stackblock() + typeloc) = subtype | flags;
1741 if (subtype != VSNORMAL) {
1742 if (level + 1 >= maxnest) {
1744 if (state == state_static) {
1745 state = parser_temp_alloc(
1746 maxnest * sizeof(*state));
1747 memcpy(state, state_static,
1748 MAXNEST_STATIC * sizeof(*state));
1750 state = parser_temp_realloc(state,
1751 maxnest * sizeof(*state));
1754 state[level].parenlevel = 0;
1755 if (subtype == VSMINUS || subtype == VSPLUS ||
1756 subtype == VSQUESTION || subtype == VSASSIGN) {
1758 * For operators that were in the Bourne shell,
1759 * inherit the double-quote state.
1761 state[level].syntax = state[level - 1].syntax;
1762 state[level].category = TSTATE_VAR_OLD;
1765 * The other operators take a pattern,
1766 * so go to BASESYNTAX.
1767 * Also, ' and " are now special, even
1768 * in here documents.
1770 state[level].syntax = BASESYNTAX;
1771 state[level].category = TSTATE_VAR_NEW;
1775 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1776 /* $'cstylequotes' */
1777 USTPUTC(CTLQUOTEMARK, out);
1778 state[level].syntax = SQSYNTAX;
1784 goto parsesub_return;
1789 * Parse an arithmetic expansion (indicate start of one and set state)
1793 if (level + 1 >= maxnest) {
1795 if (state == state_static) {
1796 state = parser_temp_alloc(
1797 maxnest * sizeof(*state));
1798 memcpy(state, state_static,
1799 MAXNEST_STATIC * sizeof(*state));
1801 state = parser_temp_realloc(state,
1802 maxnest * sizeof(*state));
1805 state[level].syntax = ARISYNTAX;
1806 state[level].parenlevel = 0;
1807 state[level].category = TSTATE_ARITH;
1808 USTPUTC(CTLARI, out);
1809 if (state[level - 1].syntax == DQSYNTAX)
1813 goto parsearith_return;
1816 } /* end of readtoken */
1828 * Returns true if the text contains nothing to expand (no dollar signs
1833 noexpand(char *text)
1839 while ((c = *p++) != '\0') {
1840 if ( c == CTLQUOTEMARK)
1844 else if (BASESYNTAX[(int)c] == CCTL)
1852 * Return true if the argument is a legal variable name (a letter or
1853 * underscore followed by zero or more letters, underscores, and digits).
1857 goodname(const char *name)
1865 if (! is_in_name(*p))
1873 isassignment(const char *p)
1881 else if (!is_in_name(*p))
1889 * Called when an unexpected token is read during the parse. The argument
1890 * is the token that is expected, or -1 if more than one type of token can
1891 * occur at this point.
1895 synexpect(int token)
1900 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1901 tokname[lasttoken], tokname[token]);
1903 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1910 synerror(const char *msg)
1913 outfmt(out2, "%s: %d: ", commandname, startlinno);
1914 outfmt(out2, "Syntax error: %s\n", msg);
1919 setprompt(int which)
1921 whichprompt = which;
1927 out2str(getprompt(NULL));
1933 * called by editline -- any expansions to the prompt
1934 * should be added here.
1937 getprompt(void *unused __unused)
1939 static char ps[PROMPTLEN];
1945 * Select prompt format.
1947 switch (whichprompt) {
1962 * Format prompt string.
1964 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1971 * \h specifies just the local hostname,
1972 * \H specifies fully-qualified hostname.
1977 gethostname(&ps[i], PROMPTLEN - i);
1978 /* Skip to end of hostname. */
1979 trim = (*fmt == 'h') ? '.' : '\0';
1980 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1985 * Working directory.
1987 * \W specifies just the final component,
1988 * \w specifies the entire path.
1992 pwd = lookupvar("PWD");
1996 *pwd == '/' && pwd[1] != '\0')
1997 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2000 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2001 /* Skip to end of path. */
2002 while (ps[i + 1] != '\0')
2009 * '$' for normal users, '#' for root.
2012 ps[i] = (geteuid() != 0) ? '$' : '#';
2023 * Emit unrecognized formats verbatim.
2041 struct jmploc jmploc;
2042 struct jmploc *const savehandler = handler;
2043 const int saveprompt = doprompt;
2044 struct parsefile *const savetopfile = getcurrentfile();
2045 struct parser_temp *const saveparser_temp = parser_temp;
2046 const char *result = NULL;
2048 if (!setjmp(jmploc.loc)) {
2051 setinputstring(ps, 1);
2053 readtoken1(pgetc(), DQSYNTAX, __DECONST(char *, "\n\n"), 0);
2054 if (backquotelist != NULL)
2055 error("Command substitution not allowed here");
2059 n.narg.text = wordtext;
2060 n.narg.backquote = backquotelist;
2062 expandarg(&n, NULL, 0);
2063 result = stackblock();
2066 handler = savehandler;
2067 doprompt = saveprompt;
2068 popfilesupto(savetopfile);
2069 if (parser_temp != saveparser_temp) {
2070 parser_temp_free_all();
2071 parser_temp = saveparser_temp;
2073 if (result != NULL) {
2075 } else if (exception == EXINT)