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. 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 253659 2013-07-25 20:50:35Z 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 int tokpushback; /* last token pushed back */
95 static char *wordtext; /* text of last word returned by readtoken */
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, const 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, const char *eofmark,
1302 char * volatile out;
1304 char line[EOFMARKLEN + 1];
1305 struct nodelist *bqlist;
1306 volatile int quotef;
1310 struct tokenstate state_static[MAXNEST_STATIC];
1311 int maxnest = MAXNEST_STATIC;
1312 struct tokenstate *state = state_static;
1315 startlinno = plinno;
1320 state[level].syntax = initialsyntax;
1321 state[level].parenlevel = 0;
1322 state[level].category = TSTATE_TOP;
1325 loop: { /* for each line, until end of word */
1326 CHECKEND(); /* set c to PEOF if at end of here document */
1327 for (;;) { /* until end of line or end of word */
1328 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1330 synentry = state[level].syntax[c];
1333 case CNL: /* '\n' */
1334 if (state[level].syntax == BASESYNTAX)
1335 goto endword; /* exit outer loop */
1343 goto loop; /* continue outer loop */
1346 out = readcstyleesc(out);
1354 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1355 USTPUTC(CTLESC, out);
1358 case CBACK: /* backslash */
1363 } else if (c == '\n') {
1370 if (state[level].syntax == DQSYNTAX &&
1371 c != '\\' && c != '`' && c != '$' &&
1372 (c != '"' || (eofmark != NULL &&
1373 newvarnest == 0)) &&
1374 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1376 if ((eofmark == NULL ||
1378 state[level].syntax == BASESYNTAX)
1379 USTPUTC(CTLQUOTEMARK, out);
1380 if (SQSYNTAX[c] == CCTL)
1381 USTPUTC(CTLESC, out);
1383 if ((eofmark == NULL ||
1385 state[level].syntax == BASESYNTAX &&
1386 state[level].category == TSTATE_VAR_OLD)
1387 USTPUTC(CTLQUOTEEND, out);
1392 USTPUTC(CTLQUOTEMARK, out);
1393 state[level].syntax = SQSYNTAX;
1397 USTPUTC(CTLQUOTEMARK, out);
1398 state[level].syntax = DQSYNTAX;
1401 if (eofmark != NULL && newvarnest == 0)
1404 if (state[level].category == TSTATE_VAR_OLD)
1405 USTPUTC(CTLQUOTEEND, out);
1406 state[level].syntax = BASESYNTAX;
1410 case CVAR: /* '$' */
1411 PARSESUB(); /* parse substitution */
1413 case CENDVAR: /* '}' */
1415 ((state[level].category == TSTATE_VAR_OLD &&
1416 state[level].syntax ==
1417 state[level - 1].syntax) ||
1418 (state[level].category == TSTATE_VAR_NEW &&
1419 state[level].syntax == BASESYNTAX))) {
1420 if (state[level].category == TSTATE_VAR_NEW)
1423 USTPUTC(CTLENDVAR, out);
1428 case CLP: /* '(' in arithmetic */
1429 state[level].parenlevel++;
1432 case CRP: /* ')' in arithmetic */
1433 if (state[level].parenlevel > 0) {
1435 --state[level].parenlevel;
1437 if (pgetc() == ')') {
1439 state[level].category == TSTATE_ARITH) {
1441 USTPUTC(CTLENDARI, out);
1447 * (don't 2nd guess - no error)
1454 case CBQUOTE: /* '`' */
1455 out = parsebackq(out, &bqlist, 1,
1456 state[level].syntax == DQSYNTAX &&
1457 (eofmark == NULL || newvarnest > 0),
1458 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1461 goto endword; /* exit outer loop */
1466 goto endword; /* exit outer loop */
1473 if (state[level].syntax == ARISYNTAX)
1474 synerror("Missing '))'");
1475 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1476 synerror("Unterminated quoted string");
1477 if (state[level].category == TSTATE_VAR_OLD ||
1478 state[level].category == TSTATE_VAR_NEW) {
1479 startlinno = plinno;
1480 synerror("Missing '}'");
1482 if (state != state_static)
1483 parser_temp_free_upto(state);
1485 len = out - stackblock();
1487 if (eofmark == NULL) {
1488 if ((c == '>' || c == '<')
1491 && (*out == '\0' || is_digit(*out))) {
1493 return lasttoken = TREDIR;
1499 backquotelist = bqlist;
1500 grabstackblock(len);
1502 return lasttoken = TWORD;
1503 /* end of readtoken routine */
1507 * Check to see whether we are at the end of the here document. When this
1508 * is called, c is set to the first character of the next input line. If
1509 * we are at the end of the here document, this routine sets the c to PEOF.
1518 if (c == *eofmark) {
1519 if (pfgets(line, sizeof line) != NULL) {
1523 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1524 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1528 needprompt = doprompt;
1531 pushstring(line, strlen(line), NULL);
1536 goto checkend_return;
1541 * Parse a redirection operator. The variable "out" points to a string
1542 * specifying the fd to be redirected. The variable "c" contains the
1543 * first character of the redirection operator.
1550 np = (union node *)stalloc(sizeof (struct nfile));
1559 np->type = NCLOBBER;
1564 } else { /* c == '<' */
1568 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1569 np = (union node *)stalloc(sizeof (struct nhere));
1573 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1575 if ((c = pgetc()) == '-') {
1576 heredoc->striptabs = 1;
1578 heredoc->striptabs = 0;
1581 } else if (c == '&')
1591 np->nfile.fd = digit_val(fd);
1593 goto parseredir_return;
1598 * Parse a substitution. At this point, we have read the dollar sign
1608 static const char types[] = "}-+?=";
1609 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1615 if (c == '(') { /* $(command) or $((arith)) */
1616 if (pgetc() == '(') {
1620 out = parsebackq(out, &bqlist, 0,
1621 state[level].syntax == DQSYNTAX &&
1622 (eofmark == NULL || newvarnest > 0),
1623 state[level].syntax == DQSYNTAX ||
1624 state[level].syntax == ARISYNTAX);
1626 } else if (c == '{' || is_name(c) || is_special(c)) {
1627 USTPUTC(CTLVAR, out);
1628 typeloc = out - stackblock();
1629 USTPUTC(VSNORMAL, out);
1638 if (!is_eof(c) && is_name(c)) {
1644 } while (!is_eof(c) && is_in_name(c));
1646 strncmp(out - length, "LINENO", length) == 0) {
1647 /* Replace the variable name with the
1648 * current line number. */
1651 linno -= funclinno - 1;
1652 snprintf(buf, sizeof(buf), "%d", linno);
1657 } else if (is_digit(c)) {
1658 if (bracketed_name) {
1662 } while (is_digit(c));
1667 } else if (is_special(c)) {
1670 if (subtype == 0 && c1 == '#') {
1672 if (strchr(types, c) == NULL && c != ':' &&
1673 c != '#' && c != '%')
1677 if (c1 != '}' && c == '}') {
1692 else if (c == '\n' || c == PEOF)
1693 synerror("Unexpected end of line in substitution");
1704 p = strchr(types, c);
1706 if (c == '\n' || c == PEOF)
1707 synerror("Unexpected end of line in substitution");
1713 subtype = p - types + VSNORMAL;
1719 subtype = c == '#' ? VSTRIMLEFT :
1729 } else if (subtype != VSERROR) {
1730 if (subtype == VSLENGTH && c != '}')
1735 if (state[level].syntax == DQSYNTAX ||
1736 state[level].syntax == ARISYNTAX)
1738 *(stackblock() + typeloc) = subtype | flags;
1739 if (subtype != VSNORMAL) {
1740 if (level + 1 >= maxnest) {
1742 if (state == state_static) {
1743 state = parser_temp_alloc(
1744 maxnest * sizeof(*state));
1745 memcpy(state, state_static,
1746 MAXNEST_STATIC * sizeof(*state));
1748 state = parser_temp_realloc(state,
1749 maxnest * sizeof(*state));
1752 state[level].parenlevel = 0;
1753 if (subtype == VSMINUS || subtype == VSPLUS ||
1754 subtype == VSQUESTION || subtype == VSASSIGN) {
1756 * For operators that were in the Bourne shell,
1757 * inherit the double-quote state.
1759 state[level].syntax = state[level - 1].syntax;
1760 state[level].category = TSTATE_VAR_OLD;
1763 * The other operators take a pattern,
1764 * so go to BASESYNTAX.
1765 * Also, ' and " are now special, even
1766 * in here documents.
1768 state[level].syntax = BASESYNTAX;
1769 state[level].category = TSTATE_VAR_NEW;
1773 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1774 /* $'cstylequotes' */
1775 USTPUTC(CTLQUOTEMARK, out);
1776 state[level].syntax = SQSYNTAX;
1782 goto parsesub_return;
1787 * Parse an arithmetic expansion (indicate start of one and set state)
1791 if (level + 1 >= maxnest) {
1793 if (state == state_static) {
1794 state = parser_temp_alloc(
1795 maxnest * sizeof(*state));
1796 memcpy(state, state_static,
1797 MAXNEST_STATIC * sizeof(*state));
1799 state = parser_temp_realloc(state,
1800 maxnest * sizeof(*state));
1803 state[level].syntax = ARISYNTAX;
1804 state[level].parenlevel = 0;
1805 state[level].category = TSTATE_ARITH;
1806 USTPUTC(CTLARI, out);
1807 if (state[level - 1].syntax == DQSYNTAX)
1811 goto parsearith_return;
1814 } /* end of readtoken */
1826 * Returns true if the text contains nothing to expand (no dollar signs
1831 noexpand(char *text)
1837 while ((c = *p++) != '\0') {
1838 if ( c == CTLQUOTEMARK)
1842 else if (BASESYNTAX[(int)c] == CCTL)
1850 * Return true if the argument is a legal variable name (a letter or
1851 * underscore followed by zero or more letters, underscores, and digits).
1855 goodname(const char *name)
1863 if (! is_in_name(*p))
1871 isassignment(const char *p)
1879 else if (!is_in_name(*p))
1887 * Called when an unexpected token is read during the parse. The argument
1888 * is the token that is expected, or -1 if more than one type of token can
1889 * occur at this point.
1893 synexpect(int token)
1898 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1899 tokname[lasttoken], tokname[token]);
1901 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1908 synerror(const char *msg)
1911 outfmt(out2, "%s: %d: ", commandname, startlinno);
1912 outfmt(out2, "Syntax error: %s\n", msg);
1917 setprompt(int which)
1919 whichprompt = which;
1925 out2str(getprompt(NULL));
1931 * called by editline -- any expansions to the prompt
1932 * should be added here.
1935 getprompt(void *unused __unused)
1937 static char ps[PROMPTLEN];
1943 * Select prompt format.
1945 switch (whichprompt) {
1960 * Format prompt string.
1962 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1969 * \h specifies just the local hostname,
1970 * \H specifies fully-qualified hostname.
1975 gethostname(&ps[i], PROMPTLEN - i);
1976 /* Skip to end of hostname. */
1977 trim = (*fmt == 'h') ? '.' : '\0';
1978 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1983 * Working directory.
1985 * \W specifies just the final component,
1986 * \w specifies the entire path.
1990 pwd = lookupvar("PWD");
1994 *pwd == '/' && pwd[1] != '\0')
1995 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1998 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1999 /* Skip to end of path. */
2000 while (ps[i + 1] != '\0')
2007 * '$' for normal users, '#' for root.
2010 ps[i] = (geteuid() != 0) ? '$' : '#';
2021 * Emit unrecognized formats verbatim.
2036 expandstr(const char *ps)
2039 struct jmploc jmploc;
2040 struct jmploc *const savehandler = handler;
2041 const int saveprompt = doprompt;
2042 struct parsefile *const savetopfile = getcurrentfile();
2043 struct parser_temp *const saveparser_temp = parser_temp;
2044 const char *result = NULL;
2046 if (!setjmp(jmploc.loc)) {
2049 setinputstring(ps, 1);
2051 readtoken1(pgetc(), DQSYNTAX, __DECONST(char *, "\n\n"), 0);
2052 if (backquotelist != NULL)
2053 error("Command substitution not allowed here");
2057 n.narg.text = wordtext;
2058 n.narg.backquote = backquotelist;
2060 expandarg(&n, NULL, 0);
2061 result = stackblock();
2064 handler = savehandler;
2065 doprompt = saveprompt;
2066 popfilesupto(savetopfile);
2067 if (parser_temp != saveparser_temp) {
2068 parser_temp_free_all();
2069 parser_temp = saveparser_temp;
2071 if (result != NULL) {
2073 } else if (exception == EXINT)