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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)parser.c 8.7 (Berkeley) 5/16/95
33 * $FreeBSD: head/bin/sh/parser.c 245382 2013-01-13 19:26:33Z jilles $
43 #include "expand.h" /* defines rmescapes() */
55 #include "exec.h" /* to check for special builtins */
57 #include "myhistedit.h"
61 * Shell command parser.
67 /* values of checkkwd variable */
72 /* values returned by readtoken */
78 struct heredoc *next; /* next here document in list */
79 union node *here; /* redirection node */
80 char *eofmark; /* string indicating end of input */
81 int striptabs; /* if set, strip leading tabs */
85 struct parser_temp *next;
90 static struct heredoc *heredoclist; /* list of here documents to read */
91 static int doprompt; /* if set, prompt the user */
92 static int needprompt; /* true if interactive and at start of line */
93 static int lasttoken; /* last token read */
94 MKINIT int tokpushback; /* last token pushed back */
95 static char *wordtext; /* text of last word returned by readtoken */
96 MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
97 static struct nodelist *backquotelist;
98 static union node *redirnode;
99 static struct heredoc *heredoc;
100 static int quoteflag; /* set if (part of) last token was quoted */
101 static int startlinno; /* line # where last token started */
102 static int funclinno; /* line # where the current function started */
103 static struct parser_temp *parser_temp;
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 void parseheredoc(void);
114 static int peektoken(void);
115 static int readtoken(void);
116 static int xxreadtoken(void);
117 static int readtoken1(int, char const *, char *, int);
118 static int noexpand(char *);
119 static void synexpect(int) __dead2;
120 static void synerror(const char *) __dead2;
121 static void setprompt(int);
125 parser_temp_alloc(size_t len)
127 struct parser_temp *t;
130 t = ckmalloc(sizeof(*t));
132 t->next = parser_temp;
134 t->data = ckmalloc(len);
141 parser_temp_realloc(void *ptr, size_t len)
143 struct parser_temp *t;
148 error("bug: parser_temp_realloc misused");
149 t->data = ckrealloc(t->data, len);
156 parser_temp_free_upto(void *ptr)
158 struct parser_temp *t;
162 while (parser_temp != NULL && !done) {
164 parser_temp = t->next;
165 done = t->data == ptr;
171 error("bug: parser_temp_free_upto misused");
176 parser_temp_free_all(void)
178 struct parser_temp *t;
181 while (parser_temp != NULL) {
183 parser_temp = t->next;
192 * Read and parse a command. Returns NEOF on end of file. (NULL is a
193 * valid parse tree indicating a blank line.)
197 parsecmd(int interact)
201 /* This assumes the parser is not re-entered,
202 * which could happen if we add command substitution on PS1/PS2.
204 parser_temp_free_all();
225 list(int nlflag, int erflag)
227 union node *ntop, *n1, *n2, *n3;
230 checkkwd = CHKNL | CHKKWD | CHKALIAS;
231 if (!nlflag && !erflag && tokendlist[peektoken()])
237 if (tok == TBACKGND) {
238 if (n2 != NULL && n2->type == NPIPE) {
239 n2->npipe.backgnd = 1;
240 } else if (n2 != NULL && n2->type == NREDIR) {
243 n3 = (union node *)stalloc(sizeof (struct nredir));
246 n3->nredir.redirect = NULL;
252 else if (n1 == NULL) {
253 n1 = (union node *)stalloc(sizeof (struct nbinary));
255 n1->nbinary.ch1 = ntop;
256 n1->nbinary.ch2 = n2;
260 n3 = (union node *)stalloc(sizeof (struct nbinary));
262 n3->nbinary.ch1 = n1->nbinary.ch2;
263 n3->nbinary.ch2 = n2;
264 n1->nbinary.ch2 = n3;
277 } else if (tok == TEOF && nlflag) {
283 checkkwd = CHKNL | CHKKWD | CHKALIAS;
284 if (!nlflag && (erflag ? peektoken() == TEOF :
285 tokendlist[peektoken()]))
292 pungetc(); /* push back EOF on input */
295 if (nlflag || erflag)
308 union node *n1, *n2, *n3;
313 if ((t = readtoken()) == TAND) {
315 } else if (t == TOR) {
322 n3 = (union node *)stalloc(sizeof (struct nbinary));
324 n3->nbinary.ch1 = n1;
325 n3->nbinary.ch2 = n2;
335 union node *n1, *n2, *pipenode;
336 struct nodelist *lp, *prev;
340 checkkwd = CHKNL | CHKKWD | CHKALIAS;
341 TRACE(("pipeline: entered\n"));
342 while (readtoken() == TNOT)
346 if (readtoken() == TPIPE) {
347 pipenode = (union node *)stalloc(sizeof (struct npipe));
348 pipenode->type = NPIPE;
349 pipenode->npipe.backgnd = 0;
350 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
351 pipenode->npipe.cmdlist = lp;
355 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
356 checkkwd = CHKNL | CHKKWD | CHKALIAS;
364 } while (readtoken() == TPIPE);
370 n2 = (union node *)stalloc(sizeof (struct nnot));
384 union node *ap, **app;
385 union node *cp, **cpp;
386 union node *redir, **rpp;
390 checkkwd = CHKNL | CHKKWD | CHKALIAS;
396 /* Check for redirection which may precede command */
397 while (readtoken() == TREDIR) {
398 *rpp = n2 = redirnode;
399 rpp = &n2->nfile.next;
404 switch (readtoken()) {
406 n1 = (union node *)stalloc(sizeof (struct nif));
408 if ((n1->nif.test = list(0, 0)) == NULL)
410 if (readtoken() != TTHEN)
412 n1->nif.ifpart = list(0, 0);
414 while (readtoken() == TELIF) {
415 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
416 n2 = n2->nif.elsepart;
418 if ((n2->nif.test = list(0, 0)) == NULL)
420 if (readtoken() != TTHEN)
422 n2->nif.ifpart = list(0, 0);
424 if (lasttoken == TELSE)
425 n2->nif.elsepart = list(0, 0);
427 n2->nif.elsepart = NULL;
430 if (readtoken() != TFI)
432 checkkwd = CHKKWD | CHKALIAS;
437 n1 = (union node *)stalloc(sizeof (struct nbinary));
438 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
439 if ((n1->nbinary.ch1 = list(0, 0)) == NULL)
441 if ((got=readtoken()) != TDO) {
442 TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
445 n1->nbinary.ch2 = list(0, 0);
446 if (readtoken() != TDONE)
448 checkkwd = CHKKWD | CHKALIAS;
452 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
453 synerror("Bad for loop variable");
454 n1 = (union node *)stalloc(sizeof (struct nfor));
456 n1->nfor.var = wordtext;
457 while (readtoken() == TNL)
459 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
461 while (readtoken() == TWORD) {
462 n2 = (union node *)stalloc(sizeof (struct narg));
464 n2->narg.text = wordtext;
465 n2->narg.backquote = backquotelist;
467 app = &n2->narg.next;
471 if (lasttoken != TNL && lasttoken != TSEMI)
474 static char argvars[5] = {
475 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
477 n2 = (union node *)stalloc(sizeof (struct narg));
479 n2->narg.text = argvars;
480 n2->narg.backquote = NULL;
481 n2->narg.next = NULL;
484 * Newline or semicolon here is optional (but note
485 * that the original Bourne shell only allowed NL).
487 if (lasttoken != TNL && lasttoken != TSEMI)
490 checkkwd = CHKNL | CHKKWD | CHKALIAS;
491 if ((t = readtoken()) == TDO)
493 else if (t == TBEGIN)
497 n1->nfor.body = list(0, 0);
498 if (readtoken() != t)
500 checkkwd = CHKKWD | CHKALIAS;
503 n1 = (union node *)stalloc(sizeof (struct ncase));
505 if (readtoken() != TWORD)
507 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
509 n2->narg.text = wordtext;
510 n2->narg.backquote = backquotelist;
511 n2->narg.next = NULL;
512 while (readtoken() == TNL);
513 if (lasttoken != TWORD || ! equal(wordtext, "in"))
514 synerror("expecting \"in\"");
515 cpp = &n1->ncase.cases;
516 checkkwd = CHKNL | CHKKWD, readtoken();
517 while (lasttoken != TESAC) {
518 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
520 app = &cp->nclist.pattern;
521 if (lasttoken == TLP)
524 *app = ap = (union node *)stalloc(sizeof (struct narg));
526 ap->narg.text = wordtext;
527 ap->narg.backquote = backquotelist;
528 checkkwd = CHKNL | CHKKWD;
529 if (readtoken() != TPIPE)
531 app = &ap->narg.next;
534 ap->narg.next = NULL;
535 if (lasttoken != TRP)
537 cp->nclist.body = list(0, 0);
539 checkkwd = CHKNL | CHKKWD | CHKALIAS;
540 if ((t = readtoken()) != TESAC) {
543 else if (t == TFALLTHRU)
544 cp->type = NCLISTFALLTHRU;
547 checkkwd = CHKNL | CHKKWD, readtoken();
549 cpp = &cp->nclist.next;
552 checkkwd = CHKKWD | CHKALIAS;
555 n1 = (union node *)stalloc(sizeof (struct nredir));
556 n1->type = NSUBSHELL;
557 n1->nredir.n = list(0, 0);
558 n1->nredir.redirect = NULL;
559 if (readtoken() != TRP)
561 checkkwd = CHKKWD | CHKALIAS;
566 if (readtoken() != TEND)
568 checkkwd = CHKKWD | CHKALIAS;
570 /* Handle an empty command like other simple commands. */
576 * An empty command before a ; doesn't make much sense, and
577 * should certainly be disallowed in the case of `if ;'.
586 n1 = simplecmd(rpp, redir);
592 /* Now check for redirection which may follow command */
593 while (readtoken() == TREDIR) {
594 *rpp = n2 = redirnode;
595 rpp = &n2->nfile.next;
602 n2 = (union node *)stalloc(sizeof (struct nredir));
607 n1->nredir.redirect = redir;
615 simplecmd(union node **rpp, union node *redir)
617 union node *args, **app;
618 union node **orig_rpp = rpp;
619 union node *n = NULL;
623 /* If we don't have any redirections already, then we must reset */
624 /* rpp to be the address of the local redir variable. */
631 * We save the incoming value, because we need this for shell
632 * functions. There can not be a redirect or an argument between
633 * the function name and the open parenthesis.
637 savecheckkwd = CHKALIAS;
640 checkkwd = savecheckkwd;
641 if (readtoken() == TWORD) {
642 n = (union node *)stalloc(sizeof (struct narg));
644 n->narg.text = wordtext;
645 n->narg.backquote = backquotelist;
648 if (savecheckkwd != 0 && !isassignment(wordtext))
650 } else if (lasttoken == TREDIR) {
651 *rpp = n = redirnode;
652 rpp = &n->nfile.next;
653 parsefname(); /* read name of redirection file */
654 } else if (lasttoken == TLP && app == &args->narg.next
655 && rpp == orig_rpp) {
656 /* We have a function */
657 if (readtoken() != TRP)
661 * - Require plain text.
662 * - Functions with '/' cannot be called.
664 * - Reject ksh extended glob patterns.
666 if (!noexpand(n->narg.text) || quoteflag ||
667 strchr(n->narg.text, '/') ||
669 n->narg.text[strlen(n->narg.text) - 1]))
670 synerror("Bad function name");
671 rmescapes(n->narg.text);
672 if (find_builtin(n->narg.text, &special) >= 0 &&
674 synerror("Cannot override a special builtin with a function");
676 n->narg.next = command();
686 n = (union node *)stalloc(sizeof (struct ncmd));
689 n->ncmd.redirect = redir;
698 n = (union node *)stalloc(sizeof (struct narg));
701 n->narg.text = wordtext;
702 n->narg.backquote = backquotelist;
707 fixredir(union node *n, const char *text, int err)
709 TRACE(("Fix redir %s %d\n", text, err));
711 n->ndup.vname = NULL;
713 if (is_digit(text[0]) && text[1] == '\0')
714 n->ndup.dupfd = digit_val(text[0]);
715 else if (text[0] == '-' && text[1] == '\0')
720 synerror("Bad fd number");
722 n->ndup.vname = makename();
730 union node *n = redirnode;
732 if (readtoken() != TWORD)
734 if (n->type == NHERE) {
735 struct heredoc *here = heredoc;
741 TRACE(("Here document %d\n", n->type));
742 if (here->striptabs) {
743 while (*wordtext == '\t')
746 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
747 synerror("Illegal eof marker for << redirection");
749 here->eofmark = wordtext;
751 if (heredoclist == NULL)
754 for (p = heredoclist ; p->next ; p = p->next);
757 } else if (n->type == NTOFD || n->type == NFROMFD) {
758 fixredir(n, wordtext, 0);
760 n->nfile.fname = makename();
766 * Input any here documents.
772 struct heredoc *here;
775 while (heredoclist) {
777 heredoclist = here->next;
782 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
783 here->eofmark, here->striptabs);
784 n = (union node *)stalloc(sizeof (struct narg));
787 n->narg.text = wordtext;
788 n->narg.backquote = backquotelist;
789 here->here->nhere.doc = n;
809 int alreadyseen = tokpushback;
818 if (checkkwd & CHKNL) {
826 * check for keywords and aliases
828 if (t == TWORD && !quoteflag)
830 const char * const *pp;
832 if (checkkwd & CHKKWD)
833 for (pp = parsekwd; *pp; pp++) {
834 if (**pp == *wordtext && equal(*pp, wordtext))
836 lasttoken = t = pp - parsekwd + KWDOFFSET;
837 TRACE(("keyword %s recognized\n", tokname[t]));
841 if (checkkwd & CHKALIAS &&
842 (ap = lookupalias(wordtext, 1)) != NULL) {
843 pushstring(ap->val, strlen(ap->val), ap);
853 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
855 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
862 * Read the next input token.
863 * If the token is a word, we set backquotelist to the list of cmds in
864 * backquotes. We set quoteflag to true if any part of the word was
866 * If the token is TREDIR, then we set redirnode to a structure containing
868 * In all cases, the variable startlinno is set to the number of the line
869 * on which the token starts.
871 * [Change comment: here documents and internal procedures]
872 * [Readtoken shouldn't have any arguments. Perhaps we should make the
873 * word parsing code into a separate routine. In this case, readtoken
874 * doesn't need to have any internal procedures, but parseword does.
875 * We could also make parseoperator in essence the main routine, and
876 * have parseword (readtoken1?) handle both words and redirection.]
879 #define RETURN(token) return lasttoken = token
895 for (;;) { /* until token or start of word found */
901 while ((c = pgetc()) != '\n' && c != PEOF);
905 if (pgetc() == '\n') {
906 startlinno = ++plinno;
917 needprompt = doprompt;
948 return readtoken1(c, BASESYNTAX, NULL, 0);
953 #define MAXNEST_STATIC 8
956 const char *syntax; /* *SYNTAX */
957 int parenlevel; /* levels of parentheses in arithmetic */
958 enum tokenstate_category
961 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
962 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
969 * Called to parse command substitutions.
973 parsebackq(char *out, struct nodelist **pbqlist,
974 int oldstyle, int dblquote, int quoted)
976 struct nodelist **nlpp;
979 struct jmploc jmploc;
980 struct jmploc *const savehandler = handler;
983 const int bq_startlinno = plinno;
984 char *volatile ostr = NULL;
985 struct parsefile *const savetopfile = getcurrentfile();
986 struct heredoc *const saveheredoclist = heredoclist;
987 struct heredoc *here;
990 if (setjmp(jmploc.loc)) {
991 popfilesupto(savetopfile);
996 heredoclist = saveheredoclist;
997 handler = savehandler;
998 if (exception == EXERROR) {
999 startlinno = bq_startlinno;
1000 synerror("Error in command substitution");
1002 longjmp(handler->loc, 1);
1005 savelen = out - stackblock();
1007 str = ckmalloc(savelen);
1008 memcpy(str, stackblock(), savelen);
1015 * We must read until the closing backquote, giving special
1016 * treatment to some slashes, and then push the string and
1017 * reread it as input, interpreting it normally.
1022 STARTSTACKSTR(oout);
1028 CHECKSTRSPACE(2, oout);
1029 switch (c = pgetc()) {
1034 if ((c = pgetc()) == '\n') {
1041 * If eating a newline, avoid putting
1042 * the newline into the new character
1043 * stream (via the USTPUTC after the
1048 if (c != '\\' && c != '`' && c != '$'
1049 && (!dblquote || c != '"'))
1050 USTPUTC('\\', oout);
1055 needprompt = doprompt;
1059 startlinno = plinno;
1060 synerror("EOF in backquote substitution");
1069 USTPUTC('\0', oout);
1070 olen = oout - stackblock();
1072 ostr = ckmalloc(olen);
1073 memcpy(ostr, stackblock(), olen);
1074 setinputstring(ostr, 1);
1079 nlpp = &(*nlpp)->next;
1080 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1081 (*nlpp)->next = NULL;
1084 saveprompt = doprompt;
1088 n = list(0, oldstyle);
1091 doprompt = saveprompt;
1093 if (readtoken() != TRP)
1100 * Start reading from old file again, ignoring any pushed back
1101 * tokens left from the backquote parsing
1107 CHECKSTRSPACE(savelen + 1, out);
1110 memcpy(out, str, savelen);
1111 STADJUST(savelen, out);
1119 here = saveheredoclist;
1121 while (here->next != NULL)
1123 here->next = heredoclist;
1124 heredoclist = saveheredoclist;
1126 handler = savehandler;
1129 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1131 USTPUTC(CTLBACKQ, out);
1137 * Called to parse a backslash escape sequence inside $'...'.
1138 * The backslash has already been read.
1141 readcstyleesc(char *out)
1148 synerror("Unterminated quoted string");
1161 case 'a': v = '\a'; break;
1162 case 'b': v = '\b'; break;
1163 case 'e': v = '\033'; break;
1164 case 'f': v = '\f'; break;
1165 case 'n': v = '\n'; break;
1166 case 'r': v = '\r'; break;
1167 case 't': v = '\t'; break;
1168 case 'v': v = '\v'; break;
1173 if (c >= '0' && c <= '9')
1174 v = (v << 4) + c - '0';
1175 else if (c >= 'A' && c <= 'F')
1176 v = (v << 4) + c - 'A' + 10;
1177 else if (c >= 'a' && c <= 'f')
1178 v = (v << 4) + c - 'a' + 10;
1184 case '0': case '1': case '2': case '3':
1185 case '4': case '5': case '6': case '7':
1188 if (c >= '0' && c <= '7') {
1192 if (c >= '0' && c <= '7') {
1202 if (c < 0x3f || c > 0x7a || c == 0x60)
1203 synerror("Bad escape sequence");
1204 if (c == '\\' && pgetc() != '\\')
1205 synerror("Bad escape sequence");
1213 n = c == 'U' ? 8 : 4;
1215 for (i = 0; i < n; i++) {
1217 if (c >= '0' && c <= '9')
1218 v = (v << 4) + c - '0';
1219 else if (c >= 'A' && c <= 'F')
1220 v = (v << 4) + c - 'A' + 10;
1221 else if (c >= 'a' && c <= 'f')
1222 v = (v << 4) + c - 'a' + 10;
1224 synerror("Bad escape sequence");
1226 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1227 synerror("Bad escape sequence");
1228 /* We really need iconv here. */
1229 if (initial_localeisutf8 && v > 127) {
1230 CHECKSTRSPACE(4, out);
1232 * We cannot use wctomb() as the locale may have
1236 USTPUTC(0xc0 | v >> 6, out);
1237 USTPUTC(0x80 | (v & 0x3f), out);
1239 } else if (v <= 0xffff) {
1240 USTPUTC(0xe0 | v >> 12, out);
1241 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1242 USTPUTC(0x80 | (v & 0x3f), out);
1244 } else if (v <= 0x10ffff) {
1245 USTPUTC(0xf0 | v >> 18, out);
1246 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1247 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1248 USTPUTC(0x80 | (v & 0x3f), out);
1256 synerror("Bad escape sequence");
1260 * We can't handle NUL bytes.
1261 * POSIX says we should skip till the closing quote.
1264 while ((c = pgetc()) != '\'') {
1268 synerror("Unterminated quoted string");
1273 if (SQSYNTAX[v] == CCTL)
1274 USTPUTC(CTLESC, out);
1281 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1282 * is not NULL, read a here document. In the latter case, eofmark is the
1283 * word which marks the end of the document and striptabs is true if
1284 * leading tabs should be stripped from the document. The argument firstc
1285 * is the first character of the input token or document.
1287 * Because C does not have internal subroutines, I have simulated them
1288 * using goto's to implement the subroutine linkage. The following macros
1289 * will run code that appears at the end of readtoken1.
1292 #define CHECKEND() {goto checkend; checkend_return:;}
1293 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1294 #define PARSESUB() {goto parsesub; parsesub_return:;}
1295 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1298 readtoken1(int firstc, char const *initialsyntax, char *eofmark, int striptabs)
1301 char * volatile out;
1303 char line[EOFMARKLEN + 1];
1304 struct nodelist *bqlist;
1305 volatile int quotef;
1309 struct tokenstate state_static[MAXNEST_STATIC];
1310 int maxnest = MAXNEST_STATIC;
1311 struct tokenstate *state = state_static;
1314 startlinno = plinno;
1319 state[level].syntax = initialsyntax;
1320 state[level].parenlevel = 0;
1321 state[level].category = TSTATE_TOP;
1324 loop: { /* for each line, until end of word */
1325 CHECKEND(); /* set c to PEOF if at end of here document */
1326 for (;;) { /* until end of line or end of word */
1327 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1329 synentry = state[level].syntax[c];
1332 case CNL: /* '\n' */
1333 if (state[level].syntax == BASESYNTAX)
1334 goto endword; /* exit outer loop */
1342 goto loop; /* continue outer loop */
1345 out = readcstyleesc(out);
1353 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1354 USTPUTC(CTLESC, out);
1357 case CBACK: /* backslash */
1362 } else if (c == '\n') {
1369 if (state[level].syntax == DQSYNTAX &&
1370 c != '\\' && c != '`' && c != '$' &&
1371 (c != '"' || (eofmark != NULL &&
1372 newvarnest == 0)) &&
1373 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1375 if ((eofmark == NULL ||
1377 state[level].syntax == BASESYNTAX)
1378 USTPUTC(CTLQUOTEMARK, out);
1379 if (SQSYNTAX[c] == CCTL)
1380 USTPUTC(CTLESC, out);
1382 if ((eofmark == NULL ||
1384 state[level].syntax == BASESYNTAX &&
1385 state[level].category == TSTATE_VAR_OLD)
1386 USTPUTC(CTLQUOTEEND, out);
1391 USTPUTC(CTLQUOTEMARK, out);
1392 state[level].syntax = SQSYNTAX;
1396 USTPUTC(CTLQUOTEMARK, out);
1397 state[level].syntax = DQSYNTAX;
1400 if (eofmark != NULL && newvarnest == 0)
1403 if (state[level].category == TSTATE_VAR_OLD)
1404 USTPUTC(CTLQUOTEEND, out);
1405 state[level].syntax = BASESYNTAX;
1409 case CVAR: /* '$' */
1410 PARSESUB(); /* parse substitution */
1412 case CENDVAR: /* '}' */
1414 ((state[level].category == TSTATE_VAR_OLD &&
1415 state[level].syntax ==
1416 state[level - 1].syntax) ||
1417 (state[level].category == TSTATE_VAR_NEW &&
1418 state[level].syntax == BASESYNTAX))) {
1419 if (state[level].category == TSTATE_VAR_NEW)
1422 USTPUTC(CTLENDVAR, out);
1427 case CLP: /* '(' in arithmetic */
1428 state[level].parenlevel++;
1431 case CRP: /* ')' in arithmetic */
1432 if (state[level].parenlevel > 0) {
1434 --state[level].parenlevel;
1436 if (pgetc() == ')') {
1438 state[level].category == TSTATE_ARITH) {
1440 USTPUTC(CTLENDARI, out);
1446 * (don't 2nd guess - no error)
1453 case CBQUOTE: /* '`' */
1454 out = parsebackq(out, &bqlist, 1,
1455 state[level].syntax == DQSYNTAX &&
1456 (eofmark == NULL || newvarnest > 0),
1457 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1460 goto endword; /* exit outer loop */
1465 goto endword; /* exit outer loop */
1472 if (state[level].syntax == ARISYNTAX)
1473 synerror("Missing '))'");
1474 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1475 synerror("Unterminated quoted string");
1476 if (state[level].category == TSTATE_VAR_OLD ||
1477 state[level].category == TSTATE_VAR_NEW) {
1478 startlinno = plinno;
1479 synerror("Missing '}'");
1481 if (state != state_static)
1482 parser_temp_free_upto(state);
1484 len = out - stackblock();
1486 if (eofmark == NULL) {
1487 if ((c == '>' || c == '<')
1490 && (*out == '\0' || is_digit(*out))) {
1492 return lasttoken = TREDIR;
1498 backquotelist = bqlist;
1499 grabstackblock(len);
1501 return lasttoken = TWORD;
1502 /* end of readtoken routine */
1506 * Check to see whether we are at the end of the here document. When this
1507 * is called, c is set to the first character of the next input line. If
1508 * we are at the end of the here document, this routine sets the c to PEOF.
1517 if (c == *eofmark) {
1518 if (pfgets(line, sizeof line) != NULL) {
1522 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1523 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1527 needprompt = doprompt;
1530 pushstring(line, strlen(line), NULL);
1535 goto checkend_return;
1540 * Parse a redirection operator. The variable "out" points to a string
1541 * specifying the fd to be redirected. The variable "c" contains the
1542 * first character of the redirection operator.
1549 np = (union node *)stalloc(sizeof (struct nfile));
1558 np->type = NCLOBBER;
1563 } else { /* c == '<' */
1567 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1568 np = (union node *)stalloc(sizeof (struct nhere));
1572 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1574 if ((c = pgetc()) == '-') {
1575 heredoc->striptabs = 1;
1577 heredoc->striptabs = 0;
1580 } else if (c == '&')
1590 np->nfile.fd = digit_val(fd);
1592 goto parseredir_return;
1597 * Parse a substitution. At this point, we have read the dollar sign
1607 static const char types[] = "}-+?=";
1608 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1614 if (c == '(') { /* $(command) or $((arith)) */
1615 if (pgetc() == '(') {
1619 out = parsebackq(out, &bqlist, 0,
1620 state[level].syntax == DQSYNTAX &&
1621 (eofmark == NULL || newvarnest > 0),
1622 state[level].syntax == DQSYNTAX ||
1623 state[level].syntax == ARISYNTAX);
1625 } else if (c == '{' || is_name(c) || is_special(c)) {
1626 USTPUTC(CTLVAR, out);
1627 typeloc = out - stackblock();
1628 USTPUTC(VSNORMAL, out);
1637 if (!is_eof(c) && is_name(c)) {
1643 } while (!is_eof(c) && is_in_name(c));
1645 strncmp(out - length, "LINENO", length) == 0) {
1646 /* Replace the variable name with the
1647 * current line number. */
1650 linno -= funclinno - 1;
1651 snprintf(buf, sizeof(buf), "%d", linno);
1656 } else if (is_digit(c)) {
1657 if (bracketed_name) {
1661 } while (is_digit(c));
1666 } else if (is_special(c)) {
1669 if (subtype == 0 && c1 == '#') {
1671 if (strchr(types, c) == NULL && c != ':' &&
1672 c != '#' && c != '%')
1676 if (c1 != '}' && c == '}') {
1691 else if (c == '\n' || c == PEOF)
1692 synerror("Unexpected end of line in substitution");
1703 p = strchr(types, c);
1705 if (c == '\n' || c == PEOF)
1706 synerror("Unexpected end of line in substitution");
1712 subtype = p - types + VSNORMAL;
1718 subtype = c == '#' ? VSTRIMLEFT :
1728 } else if (subtype != VSERROR) {
1729 if (subtype == VSLENGTH && c != '}')
1734 if (state[level].syntax == DQSYNTAX ||
1735 state[level].syntax == ARISYNTAX)
1737 *(stackblock() + typeloc) = subtype | flags;
1738 if (subtype != VSNORMAL) {
1739 if (level + 1 >= maxnest) {
1741 if (state == state_static) {
1742 state = parser_temp_alloc(
1743 maxnest * sizeof(*state));
1744 memcpy(state, state_static,
1745 MAXNEST_STATIC * sizeof(*state));
1747 state = parser_temp_realloc(state,
1748 maxnest * sizeof(*state));
1751 state[level].parenlevel = 0;
1752 if (subtype == VSMINUS || subtype == VSPLUS ||
1753 subtype == VSQUESTION || subtype == VSASSIGN) {
1755 * For operators that were in the Bourne shell,
1756 * inherit the double-quote state.
1758 state[level].syntax = state[level - 1].syntax;
1759 state[level].category = TSTATE_VAR_OLD;
1762 * The other operators take a pattern,
1763 * so go to BASESYNTAX.
1764 * Also, ' and " are now special, even
1765 * in here documents.
1767 state[level].syntax = BASESYNTAX;
1768 state[level].category = TSTATE_VAR_NEW;
1772 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1773 /* $'cstylequotes' */
1774 USTPUTC(CTLQUOTEMARK, out);
1775 state[level].syntax = SQSYNTAX;
1781 goto parsesub_return;
1786 * Parse an arithmetic expansion (indicate start of one and set state)
1790 if (level + 1 >= maxnest) {
1792 if (state == state_static) {
1793 state = parser_temp_alloc(
1794 maxnest * sizeof(*state));
1795 memcpy(state, state_static,
1796 MAXNEST_STATIC * sizeof(*state));
1798 state = parser_temp_realloc(state,
1799 maxnest * sizeof(*state));
1802 state[level].syntax = ARISYNTAX;
1803 state[level].parenlevel = 0;
1804 state[level].category = TSTATE_ARITH;
1805 USTPUTC(CTLARI, out);
1806 if (state[level - 1].syntax == DQSYNTAX)
1810 goto parsearith_return;
1813 } /* end of readtoken */
1825 * Returns true if the text contains nothing to expand (no dollar signs
1830 noexpand(char *text)
1836 while ((c = *p++) != '\0') {
1837 if ( c == CTLQUOTEMARK)
1841 else if (BASESYNTAX[(int)c] == CCTL)
1849 * Return true if the argument is a legal variable name (a letter or
1850 * underscore followed by zero or more letters, underscores, and digits).
1854 goodname(const char *name)
1862 if (! is_in_name(*p))
1870 isassignment(const char *p)
1878 else if (!is_in_name(*p))
1886 * Called when an unexpected token is read during the parse. The argument
1887 * is the token that is expected, or -1 if more than one type of token can
1888 * occur at this point.
1892 synexpect(int token)
1897 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1898 tokname[lasttoken], tokname[token]);
1900 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1907 synerror(const char *msg)
1910 outfmt(out2, "%s: %d: ", commandname, startlinno);
1911 outfmt(out2, "Syntax error: %s\n", msg);
1916 setprompt(int which)
1918 whichprompt = which;
1924 out2str(getprompt(NULL));
1930 * called by editline -- any expansions to the prompt
1931 * should be added here.
1934 getprompt(void *unused __unused)
1936 static char ps[PROMPTLEN];
1942 * Select prompt format.
1944 switch (whichprompt) {
1959 * Format prompt string.
1961 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1968 * \h specifies just the local hostname,
1969 * \H specifies fully-qualified hostname.
1974 gethostname(&ps[i], PROMPTLEN - i);
1975 /* Skip to end of hostname. */
1976 trim = (*fmt == 'h') ? '.' : '\0';
1977 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1982 * Working directory.
1984 * \W specifies just the final component,
1985 * \w specifies the entire path.
1989 pwd = lookupvar("PWD");
1993 *pwd == '/' && pwd[1] != '\0')
1994 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1997 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1998 /* Skip to end of path. */
1999 while (ps[i + 1] != '\0')
2006 * '$' for normal users, '#' for root.
2009 ps[i] = (geteuid() != 0) ? '$' : '#';
2020 * Emit unrecognized formats verbatim.
2038 struct jmploc jmploc;
2039 struct jmploc *const savehandler = handler;
2040 const int saveprompt = doprompt;
2041 struct parsefile *const savetopfile = getcurrentfile();
2042 struct parser_temp *const saveparser_temp = parser_temp;
2043 const char *result = NULL;
2045 if (!setjmp(jmploc.loc)) {
2048 setinputstring(ps, 1);
2050 readtoken1(pgetc(), DQSYNTAX, __DECONST(char *, "\n\n"), 0);
2051 if (backquotelist != NULL)
2052 error("Command substitution not allowed here");
2056 n.narg.text = wordtext;
2057 n.narg.backquote = backquotelist;
2059 expandarg(&n, NULL, 0);
2060 result = stackblock();
2063 handler = savehandler;
2064 doprompt = saveprompt;
2065 popfilesupto(savetopfile);
2066 if (parser_temp != saveparser_temp) {
2067 parser_temp_free_all();
2068 parser_temp = saveparser_temp;
2070 if (result != NULL) {
2072 } else if (exception == EXINT)