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
35 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
48 #include "expand.h" /* defines rmescapes() */
60 #include "exec.h" /* to check for special builtins */
62 #include "myhistedit.h"
66 * Shell command parser.
72 /* values of checkkwd variable */
77 /* values returned by readtoken */
83 struct heredoc *next; /* next here document in list */
84 union node *here; /* redirection node */
85 char *eofmark; /* string indicating end of input */
86 int striptabs; /* if set, strip leading tabs */
90 struct parser_temp *next;
95 static struct heredoc *heredoclist; /* list of here documents to read */
96 static int doprompt; /* if set, prompt the user */
97 static int needprompt; /* true if interactive and at start of line */
98 static int lasttoken; /* last token read */
99 static int tokpushback; /* last token pushed back */
100 static char *wordtext; /* text of last word returned by readtoken */
102 static struct nodelist *backquotelist;
103 static union node *redirnode;
104 static struct heredoc *heredoc;
105 static int quoteflag; /* set if (part of) last token was quoted */
106 static int startlinno; /* line # where last token started */
107 static int funclinno; /* line # where the current function started */
108 static struct parser_temp *parser_temp;
111 static union node *list(int);
112 static union node *andor(void);
113 static union node *pipeline(void);
114 static union node *command(void);
115 static union node *simplecmd(union node **, union node *);
116 static union node *makename(void);
117 static union node *makebinary(int type, union node *n1, union node *n2);
118 static void parsefname(void);
119 static void parseheredoc(void);
120 static int peektoken(void);
121 static int readtoken(void);
122 static int xxreadtoken(void);
123 static int readtoken1(int, const char *, const char *, int);
124 static int noexpand(char *);
125 static void consumetoken(int);
126 static void synexpect(int) __dead2;
127 static void synerror(const char *) __dead2;
128 static void setprompt(int);
132 parser_temp_alloc(size_t len)
134 struct parser_temp *t;
137 t = ckmalloc(sizeof(*t));
139 t->next = parser_temp;
141 t->data = ckmalloc(len);
148 parser_temp_realloc(void *ptr, size_t len)
150 struct parser_temp *t;
155 error("bug: parser_temp_realloc misused");
156 t->data = ckrealloc(t->data, len);
163 parser_temp_free_upto(void *ptr)
165 struct parser_temp *t;
169 while (parser_temp != NULL && !done) {
171 parser_temp = t->next;
172 done = t->data == ptr;
178 error("bug: parser_temp_free_upto misused");
183 parser_temp_free_all(void)
185 struct parser_temp *t;
188 while (parser_temp != NULL) {
190 parser_temp = t->next;
199 * Read and parse a command. Returns NEOF on end of file. (NULL is a
200 * valid parse tree indicating a blank line.)
204 parsecmd(int interact)
208 /* This assumes the parser is not re-entered,
209 * which could happen if we add command substitution on PS1/PS2.
211 parser_temp_free_all();
235 union node *ntop, *n1, *n2, *n3;
238 checkkwd = CHKNL | CHKKWD | CHKALIAS;
239 if (!nlflag && tokendlist[peektoken()])
245 if (tok == TBACKGND) {
246 if (n2 != NULL && n2->type == NPIPE) {
247 n2->npipe.backgnd = 1;
248 } else if (n2 != NULL && n2->type == NREDIR) {
251 n3 = (union node *)stalloc(sizeof (struct nredir));
254 n3->nredir.redirect = NULL;
260 else if (n1 == NULL) {
261 n1 = makebinary(NSEMI, ntop, n2);
265 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
266 n1->nbinary.ch2 = n3;
279 } else if (tok == TEOF && nlflag) {
285 checkkwd = CHKNL | CHKKWD | CHKALIAS;
286 if (!nlflag && tokendlist[peektoken()])
293 pungetc(); /* push back EOF on input */
314 if ((t = readtoken()) == TAND) {
316 } else if (t == TOR) {
322 n = makebinary(t, n, pipeline());
331 union node *n1, *n2, *pipenode;
332 struct nodelist *lp, *prev;
336 checkkwd = CHKNL | CHKKWD | CHKALIAS;
337 TRACE(("pipeline: entered\n"));
338 while (readtoken() == TNOT)
342 if (readtoken() == TPIPE) {
343 pipenode = (union node *)stalloc(sizeof (struct npipe));
344 pipenode->type = NPIPE;
345 pipenode->npipe.backgnd = 0;
346 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
347 pipenode->npipe.cmdlist = lp;
351 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
352 checkkwd = CHKNL | CHKKWD | CHKALIAS;
360 } while (readtoken() == TPIPE);
366 n2 = (union node *)stalloc(sizeof (struct nnot));
380 union node *ap, **app;
381 union node *cp, **cpp;
382 union node *redir, **rpp;
386 checkkwd = CHKNL | CHKKWD | CHKALIAS;
392 /* Check for redirection which may precede command */
393 while (readtoken() == TREDIR) {
394 *rpp = n2 = redirnode;
395 rpp = &n2->nfile.next;
400 switch (readtoken()) {
402 n1 = (union node *)stalloc(sizeof (struct nif));
404 if ((n1->nif.test = list(0)) == NULL)
407 n1->nif.ifpart = list(0);
409 while (readtoken() == TELIF) {
410 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
411 n2 = n2->nif.elsepart;
413 if ((n2->nif.test = list(0)) == NULL)
416 n2->nif.ifpart = list(0);
418 if (lasttoken == TELSE)
419 n2->nif.elsepart = list(0);
421 n2->nif.elsepart = NULL;
425 checkkwd = CHKKWD | CHKALIAS;
430 if ((n1 = list(0)) == NULL)
433 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
435 checkkwd = CHKKWD | CHKALIAS;
438 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
439 synerror("Bad for loop variable");
440 n1 = (union node *)stalloc(sizeof (struct nfor));
442 n1->nfor.var = wordtext;
443 while (readtoken() == TNL)
445 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
447 while (readtoken() == TWORD) {
450 app = &n2->narg.next;
454 if (lasttoken != TNL && lasttoken != TSEMI)
457 static char argvars[5] = {
458 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
460 n2 = (union node *)stalloc(sizeof (struct narg));
462 n2->narg.text = argvars;
463 n2->narg.backquote = NULL;
464 n2->narg.next = NULL;
467 * Newline or semicolon here is optional (but note
468 * that the original Bourne shell only allowed NL).
470 if (lasttoken != TNL && lasttoken != TSEMI)
473 checkkwd = CHKNL | CHKKWD | CHKALIAS;
474 if ((t = readtoken()) == TDO)
476 else if (t == TBEGIN)
480 n1->nfor.body = list(0);
482 checkkwd = CHKKWD | CHKALIAS;
485 n1 = (union node *)stalloc(sizeof (struct ncase));
488 n1->ncase.expr = makename();
489 while (readtoken() == TNL);
490 if (lasttoken != TWORD || ! equal(wordtext, "in"))
491 synerror("expecting \"in\"");
492 cpp = &n1->ncase.cases;
493 checkkwd = CHKNL | CHKKWD, readtoken();
494 while (lasttoken != TESAC) {
495 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
497 app = &cp->nclist.pattern;
498 if (lasttoken == TLP)
501 *app = ap = makename();
502 checkkwd = CHKNL | CHKKWD;
503 if (readtoken() != TPIPE)
505 app = &ap->narg.next;
508 ap->narg.next = NULL;
509 if (lasttoken != TRP)
511 cp->nclist.body = list(0);
513 checkkwd = CHKNL | CHKKWD | CHKALIAS;
514 if ((t = readtoken()) != TESAC) {
517 else if (t == TFALLTHRU)
518 cp->type = NCLISTFALLTHRU;
521 checkkwd = CHKNL | CHKKWD, readtoken();
523 cpp = &cp->nclist.next;
526 checkkwd = CHKKWD | CHKALIAS;
529 n1 = (union node *)stalloc(sizeof (struct nredir));
530 n1->type = NSUBSHELL;
531 n1->nredir.n = list(0);
532 n1->nredir.redirect = NULL;
534 checkkwd = CHKKWD | CHKALIAS;
540 checkkwd = CHKKWD | CHKALIAS;
542 /* A simple command must have at least one redirection or word. */
557 n1 = simplecmd(rpp, redir);
563 /* Now check for redirection which may follow command */
564 while (readtoken() == TREDIR) {
565 *rpp = n2 = redirnode;
566 rpp = &n2->nfile.next;
573 n2 = (union node *)stalloc(sizeof (struct nredir));
578 n1->nredir.redirect = redir;
586 simplecmd(union node **rpp, union node *redir)
588 union node *args, **app;
589 union node **orig_rpp = rpp;
590 union node *n = NULL;
594 /* If we don't have any redirections already, then we must reset */
595 /* rpp to be the address of the local redir variable. */
602 * We save the incoming value, because we need this for shell
603 * functions. There can not be a redirect or an argument between
604 * the function name and the open parenthesis.
608 savecheckkwd = CHKALIAS;
611 checkkwd = savecheckkwd;
612 if (readtoken() == TWORD) {
616 if (savecheckkwd != 0 && !isassignment(wordtext))
618 } else if (lasttoken == TREDIR) {
619 *rpp = n = redirnode;
620 rpp = &n->nfile.next;
621 parsefname(); /* read name of redirection file */
622 } else if (lasttoken == TLP && app == &args->narg.next
623 && rpp == orig_rpp) {
624 /* We have a function */
628 * - Require plain text.
629 * - Functions with '/' cannot be called.
631 * - Reject ksh extended glob patterns.
633 if (!noexpand(n->narg.text) || quoteflag ||
634 strchr(n->narg.text, '/') ||
636 n->narg.text[strlen(n->narg.text) - 1]))
637 synerror("Bad function name");
638 rmescapes(n->narg.text);
639 if (find_builtin(n->narg.text, &special) >= 0 &&
641 synerror("Cannot override a special builtin with a function");
643 n->narg.next = command();
653 n = (union node *)stalloc(sizeof (struct ncmd));
656 n->ncmd.redirect = redir;
665 n = (union node *)stalloc(sizeof (struct narg));
668 n->narg.text = wordtext;
669 n->narg.backquote = backquotelist;
674 makebinary(int type, union node *n1, union node *n2)
678 n = (union node *)stalloc(sizeof (struct nbinary));
686 fixredir(union node *n, const char *text, int err)
688 TRACE(("Fix redir %s %d\n", text, err));
690 n->ndup.vname = NULL;
692 if (is_digit(text[0]) && text[1] == '\0')
693 n->ndup.dupfd = digit_val(text[0]);
694 else if (text[0] == '-' && text[1] == '\0')
699 synerror("Bad fd number");
701 n->ndup.vname = makename();
709 union node *n = redirnode;
712 if (n->type == NHERE) {
713 struct heredoc *here = heredoc;
719 TRACE(("Here document %d\n", n->type));
720 if (here->striptabs) {
721 while (*wordtext == '\t')
724 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
725 synerror("Illegal eof marker for << redirection");
727 here->eofmark = wordtext;
729 if (heredoclist == NULL)
732 for (p = heredoclist ; p->next ; p = p->next);
735 } else if (n->type == NTOFD || n->type == NFROMFD) {
736 fixredir(n, wordtext, 0);
738 n->nfile.fname = makename();
744 * Input any here documents.
750 struct heredoc *here;
753 while (heredoclist) {
755 heredoclist = here->next;
760 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
761 here->eofmark, here->striptabs);
763 here->here->nhere.doc = n;
783 int alreadyseen = tokpushback;
792 if (checkkwd & CHKNL) {
800 * check for keywords and aliases
802 if (t == TWORD && !quoteflag)
804 const char * const *pp;
806 if (checkkwd & CHKKWD)
807 for (pp = parsekwd; *pp; pp++) {
808 if (**pp == *wordtext && equal(*pp, wordtext))
810 lasttoken = t = pp - parsekwd + KWDOFFSET;
811 TRACE(("keyword %s recognized\n", tokname[t]));
815 if (checkkwd & CHKALIAS &&
816 (ap = lookupalias(wordtext, 1)) != NULL) {
817 pushstring(ap->val, strlen(ap->val), ap);
827 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
829 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
836 * Read the next input token.
837 * If the token is a word, we set backquotelist to the list of cmds in
838 * backquotes. We set quoteflag to true if any part of the word was
840 * If the token is TREDIR, then we set redirnode to a structure containing
842 * In all cases, the variable startlinno is set to the number of the line
843 * on which the token starts.
845 * [Change comment: here documents and internal procedures]
846 * [Readtoken shouldn't have any arguments. Perhaps we should make the
847 * word parsing code into a separate routine. In this case, readtoken
848 * doesn't need to have any internal procedures, but parseword does.
849 * We could also make parseoperator in essence the main routine, and
850 * have parseword (readtoken1?) handle both words and redirection.]
853 #define RETURN(token) return lasttoken = token
869 for (;;) { /* until token or start of word found */
875 while ((c = pgetc()) != '\n' && c != PEOF);
879 if (pgetc() == '\n') {
880 startlinno = ++plinno;
891 needprompt = doprompt;
922 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
927 #define MAXNEST_static 8
930 const char *syntax; /* *SYNTAX */
931 int parenlevel; /* levels of parentheses in arithmetic */
932 enum tokenstate_category
935 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
936 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
943 * Called to parse command substitutions.
947 parsebackq(char *out, struct nodelist **pbqlist,
948 int oldstyle, int dblquote, int quoted)
950 struct nodelist **nlpp;
953 struct jmploc jmploc;
954 struct jmploc *const savehandler = handler;
957 const int bq_startlinno = plinno;
958 char *volatile ostr = NULL;
959 struct parsefile *const savetopfile = getcurrentfile();
960 struct heredoc *const saveheredoclist = heredoclist;
961 struct heredoc *here;
964 if (setjmp(jmploc.loc)) {
965 popfilesupto(savetopfile);
970 heredoclist = saveheredoclist;
971 handler = savehandler;
972 if (exception == EXERROR) {
973 startlinno = bq_startlinno;
974 synerror("Error in command substitution");
976 longjmp(handler->loc, 1);
979 savelen = out - stackblock();
981 str = ckmalloc(savelen);
982 memcpy(str, stackblock(), savelen);
988 /* We must read until the closing backquote, giving special
989 treatment to some slashes, and then push the string and
990 reread it as input, interpreting it normally. */
1002 CHECKSTRSPACE(2, oout);
1003 switch (c = pgetc()) {
1008 if ((c = pgetc()) == '\n') {
1015 * If eating a newline, avoid putting
1016 * the newline into the new character
1017 * stream (via the USTPUTC after the
1022 if (c != '\\' && c != '`' && c != '$'
1023 && (!dblquote || c != '"'))
1024 USTPUTC('\\', oout);
1029 needprompt = doprompt;
1033 startlinno = plinno;
1034 synerror("EOF in backquote substitution");
1043 USTPUTC('\0', oout);
1044 olen = oout - stackblock();
1046 ostr = ckmalloc(olen);
1047 memcpy(ostr, stackblock(), olen);
1048 setinputstring(ostr, 1);
1053 nlpp = &(*nlpp)->next;
1054 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1055 (*nlpp)->next = NULL;
1058 saveprompt = doprompt;
1065 if (peektoken() != TEOF)
1067 doprompt = saveprompt;
1074 * Start reading from old file again, ignoring any pushed back
1075 * tokens left from the backquote parsing
1081 CHECKSTRSPACE(savelen + 1, out);
1084 memcpy(out, str, savelen);
1085 STADJUST(savelen, out);
1093 here = saveheredoclist;
1095 while (here->next != NULL)
1097 here->next = heredoclist;
1098 heredoclist = saveheredoclist;
1100 handler = savehandler;
1103 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1105 USTPUTC(CTLBACKQ, out);
1111 * Called to parse a backslash escape sequence inside $'...'.
1112 * The backslash has already been read.
1115 readcstyleesc(char *out)
1122 synerror("Unterminated quoted string");
1135 case 'a': v = '\a'; break;
1136 case 'b': v = '\b'; break;
1137 case 'e': v = '\033'; break;
1138 case 'f': v = '\f'; break;
1139 case 'n': v = '\n'; break;
1140 case 'r': v = '\r'; break;
1141 case 't': v = '\t'; break;
1142 case 'v': v = '\v'; break;
1147 if (c >= '0' && c <= '9')
1148 v = (v << 4) + c - '0';
1149 else if (c >= 'A' && c <= 'F')
1150 v = (v << 4) + c - 'A' + 10;
1151 else if (c >= 'a' && c <= 'f')
1152 v = (v << 4) + c - 'a' + 10;
1158 case '0': case '1': case '2': case '3':
1159 case '4': case '5': case '6': case '7':
1162 if (c >= '0' && c <= '7') {
1166 if (c >= '0' && c <= '7') {
1176 if (c < 0x3f || c > 0x7a || c == 0x60)
1177 synerror("Bad escape sequence");
1178 if (c == '\\' && pgetc() != '\\')
1179 synerror("Bad escape sequence");
1187 n = c == 'U' ? 8 : 4;
1189 for (i = 0; i < n; i++) {
1191 if (c >= '0' && c <= '9')
1192 v = (v << 4) + c - '0';
1193 else if (c >= 'A' && c <= 'F')
1194 v = (v << 4) + c - 'A' + 10;
1195 else if (c >= 'a' && c <= 'f')
1196 v = (v << 4) + c - 'a' + 10;
1198 synerror("Bad escape sequence");
1200 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1201 synerror("Bad escape sequence");
1202 /* We really need iconv here. */
1203 if (initial_localeisutf8 && v > 127) {
1204 CHECKSTRSPACE(4, out);
1206 * We cannot use wctomb() as the locale may have
1210 USTPUTC(0xc0 | v >> 6, out);
1211 USTPUTC(0x80 | (v & 0x3f), out);
1213 } else if (v <= 0xffff) {
1214 USTPUTC(0xe0 | v >> 12, out);
1215 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1216 USTPUTC(0x80 | (v & 0x3f), out);
1218 } else if (v <= 0x10ffff) {
1219 USTPUTC(0xf0 | v >> 18, out);
1220 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1221 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1222 USTPUTC(0x80 | (v & 0x3f), out);
1230 synerror("Bad escape sequence");
1234 * We can't handle NUL bytes.
1235 * POSIX says we should skip till the closing quote.
1238 while ((c = pgetc()) != '\'') {
1242 synerror("Unterminated quoted string");
1247 if (SQSYNTAX[v] == CCTL)
1248 USTPUTC(CTLESC, out);
1255 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1256 * is not NULL, read a here document. In the latter case, eofmark is the
1257 * word which marks the end of the document and striptabs is true if
1258 * leading tabs should be stripped from the document. The argument firstc
1259 * is the first character of the input token or document.
1261 * Because C does not have internal subroutines, I have simulated them
1262 * using goto's to implement the subroutine linkage. The following macros
1263 * will run code that appears at the end of readtoken1.
1266 #define CHECKEND() {goto checkend; checkend_return:;}
1267 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1268 #define PARSESUB() {goto parsesub; parsesub_return:;}
1269 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1272 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1278 char line[EOFMARKLEN + 1];
1279 struct nodelist *bqlist;
1284 struct tokenstate state_static[MAXNEST_static];
1285 int maxnest = MAXNEST_static;
1286 struct tokenstate *state = state_static;
1289 startlinno = plinno;
1294 state[level].syntax = initialsyntax;
1295 state[level].parenlevel = 0;
1296 state[level].category = TSTATE_TOP;
1299 loop: { /* for each line, until end of word */
1300 CHECKEND(); /* set c to PEOF if at end of here document */
1301 for (;;) { /* until end of line or end of word */
1302 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1304 synentry = state[level].syntax[c];
1307 case CNL: /* '\n' */
1308 if (state[level].syntax == BASESYNTAX)
1309 goto endword; /* exit outer loop */
1317 goto loop; /* continue outer loop */
1320 out = readcstyleesc(out);
1328 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1329 USTPUTC(CTLESC, out);
1332 case CBACK: /* backslash */
1337 } else if (c == '\n') {
1344 if (state[level].syntax == DQSYNTAX &&
1345 c != '\\' && c != '`' && c != '$' &&
1346 (c != '"' || (eofmark != NULL &&
1347 newvarnest == 0)) &&
1348 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1350 if ((eofmark == NULL ||
1352 state[level].syntax == BASESYNTAX)
1353 USTPUTC(CTLQUOTEMARK, out);
1354 if (SQSYNTAX[c] == CCTL)
1355 USTPUTC(CTLESC, out);
1357 if ((eofmark == NULL ||
1359 state[level].syntax == BASESYNTAX &&
1360 state[level].category == TSTATE_VAR_OLD)
1361 USTPUTC(CTLQUOTEEND, out);
1366 USTPUTC(CTLQUOTEMARK, out);
1367 state[level].syntax = SQSYNTAX;
1371 USTPUTC(CTLQUOTEMARK, out);
1372 state[level].syntax = DQSYNTAX;
1375 if (eofmark != NULL && newvarnest == 0)
1378 if (state[level].category == TSTATE_VAR_OLD)
1379 USTPUTC(CTLQUOTEEND, out);
1380 state[level].syntax = BASESYNTAX;
1384 case CVAR: /* '$' */
1385 PARSESUB(); /* parse substitution */
1387 case CENDVAR: /* '}' */
1389 ((state[level].category == TSTATE_VAR_OLD &&
1390 state[level].syntax ==
1391 state[level - 1].syntax) ||
1392 (state[level].category == TSTATE_VAR_NEW &&
1393 state[level].syntax == BASESYNTAX))) {
1394 if (state[level].category == TSTATE_VAR_NEW)
1397 USTPUTC(CTLENDVAR, out);
1402 case CLP: /* '(' in arithmetic */
1403 state[level].parenlevel++;
1406 case CRP: /* ')' in arithmetic */
1407 if (state[level].parenlevel > 0) {
1409 --state[level].parenlevel;
1411 if (pgetc() == ')') {
1413 state[level].category == TSTATE_ARITH) {
1415 USTPUTC(CTLENDARI, out);
1421 * (don't 2nd guess - no error)
1428 case CBQUOTE: /* '`' */
1429 out = parsebackq(out, &bqlist, 1,
1430 state[level].syntax == DQSYNTAX &&
1431 (eofmark == NULL || newvarnest > 0),
1432 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1435 goto endword; /* exit outer loop */
1440 goto endword; /* exit outer loop */
1447 if (state[level].syntax == ARISYNTAX)
1448 synerror("Missing '))'");
1449 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1450 synerror("Unterminated quoted string");
1451 if (state[level].category == TSTATE_VAR_OLD ||
1452 state[level].category == TSTATE_VAR_NEW) {
1453 startlinno = plinno;
1454 synerror("Missing '}'");
1456 if (state != state_static)
1457 parser_temp_free_upto(state);
1459 len = out - stackblock();
1461 if (eofmark == NULL) {
1462 if ((c == '>' || c == '<')
1465 && (*out == '\0' || is_digit(*out))) {
1467 return lasttoken = TREDIR;
1473 backquotelist = bqlist;
1474 grabstackblock(len);
1476 return lasttoken = TWORD;
1477 /* end of readtoken routine */
1481 * Check to see whether we are at the end of the here document. When this
1482 * is called, c is set to the first character of the next input line. If
1483 * we are at the end of the here document, this routine sets the c to PEOF.
1492 if (c == *eofmark) {
1493 if (pfgets(line, sizeof line) != NULL) {
1497 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1498 if ((*p == '\0' || *p == '\n') && *q == '\0') {
1502 needprompt = doprompt;
1505 pushstring(line, strlen(line), NULL);
1510 goto checkend_return;
1515 * Parse a redirection operator. The variable "out" points to a string
1516 * specifying the fd to be redirected. The variable "c" contains the
1517 * first character of the redirection operator.
1524 np = (union node *)stalloc(sizeof (struct nfile));
1533 np->type = NCLOBBER;
1538 } else { /* c == '<' */
1542 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1543 np = (union node *)stalloc(sizeof (struct nhere));
1547 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1549 if ((c = pgetc()) == '-') {
1550 heredoc->striptabs = 1;
1552 heredoc->striptabs = 0;
1555 } else if (c == '&')
1565 np->nfile.fd = digit_val(fd);
1567 goto parseredir_return;
1572 * Parse a substitution. At this point, we have read the dollar sign
1582 static const char types[] = "}-+?=";
1583 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1589 if (c == '(') { /* $(command) or $((arith)) */
1590 if (pgetc() == '(') {
1594 out = parsebackq(out, &bqlist, 0,
1595 state[level].syntax == DQSYNTAX &&
1596 (eofmark == NULL || newvarnest > 0),
1597 state[level].syntax == DQSYNTAX ||
1598 state[level].syntax == ARISYNTAX);
1600 } else if (c == '{' || is_name(c) || is_special(c)) {
1601 USTPUTC(CTLVAR, out);
1602 typeloc = out - stackblock();
1603 USTPUTC(VSNORMAL, out);
1612 if (!is_eof(c) && is_name(c)) {
1618 } while (!is_eof(c) && is_in_name(c));
1620 strncmp(out - length, "LINENO", length) == 0) {
1621 /* Replace the variable name with the
1622 * current line number. */
1625 linno -= funclinno - 1;
1626 snprintf(buf, sizeof(buf), "%d", linno);
1631 } else if (is_digit(c)) {
1632 if (bracketed_name) {
1636 } while (is_digit(c));
1641 } else if (is_special(c)) {
1644 if (subtype == 0 && c1 == '#') {
1646 if (strchr(types, c) == NULL && c != ':' &&
1647 c != '#' && c != '%')
1651 if (c1 != '}' && c == '}') {
1666 else if (c == '\n' || c == PEOF)
1667 synerror("Unexpected end of line in substitution");
1678 p = strchr(types, c);
1680 if (c == '\n' || c == PEOF)
1681 synerror("Unexpected end of line in substitution");
1687 subtype = p - types + VSNORMAL;
1693 subtype = c == '#' ? VSTRIMLEFT :
1703 } else if (subtype != VSERROR) {
1704 if (subtype == VSLENGTH && c != '}')
1709 if (state[level].syntax == DQSYNTAX ||
1710 state[level].syntax == ARISYNTAX)
1712 *(stackblock() + typeloc) = subtype | flags;
1713 if (subtype != VSNORMAL) {
1714 if (level + 1 >= maxnest) {
1716 if (state == state_static) {
1717 state = parser_temp_alloc(
1718 maxnest * sizeof(*state));
1719 memcpy(state, state_static,
1720 MAXNEST_static * sizeof(*state));
1722 state = parser_temp_realloc(state,
1723 maxnest * sizeof(*state));
1726 state[level].parenlevel = 0;
1727 if (subtype == VSMINUS || subtype == VSPLUS ||
1728 subtype == VSQUESTION || subtype == VSASSIGN) {
1730 * For operators that were in the Bourne shell,
1731 * inherit the double-quote state.
1733 state[level].syntax = state[level - 1].syntax;
1734 state[level].category = TSTATE_VAR_OLD;
1737 * The other operators take a pattern,
1738 * so go to BASESYNTAX.
1739 * Also, ' and " are now special, even
1740 * in here documents.
1742 state[level].syntax = BASESYNTAX;
1743 state[level].category = TSTATE_VAR_NEW;
1747 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1748 /* $'cstylequotes' */
1749 USTPUTC(CTLQUOTEMARK, out);
1750 state[level].syntax = SQSYNTAX;
1756 goto parsesub_return;
1761 * Parse an arithmetic expansion (indicate start of one and set state)
1765 if (level + 1 >= maxnest) {
1767 if (state == state_static) {
1768 state = parser_temp_alloc(
1769 maxnest * sizeof(*state));
1770 memcpy(state, state_static,
1771 MAXNEST_static * sizeof(*state));
1773 state = parser_temp_realloc(state,
1774 maxnest * sizeof(*state));
1777 state[level].syntax = ARISYNTAX;
1778 state[level].parenlevel = 0;
1779 state[level].category = TSTATE_ARITH;
1780 USTPUTC(CTLARI, out);
1781 if (state[level - 1].syntax == DQSYNTAX)
1785 goto parsearith_return;
1788 } /* end of readtoken */
1792 * Returns true if the text contains nothing to expand (no dollar signs
1797 noexpand(char *text)
1803 while ((c = *p++) != '\0') {
1804 if ( c == CTLQUOTEMARK)
1808 else if (BASESYNTAX[(int)c] == CCTL)
1816 * Return true if the argument is a legal variable name (a letter or
1817 * underscore followed by zero or more letters, underscores, and digits).
1821 goodname(const char *name)
1829 if (! is_in_name(*p))
1837 isassignment(const char *p)
1845 else if (!is_in_name(*p))
1853 consumetoken(int token)
1855 if (readtoken() != token)
1861 * Called when an unexpected token is read during the parse. The argument
1862 * is the token that is expected, or -1 if more than one type of token can
1863 * occur at this point.
1867 synexpect(int token)
1872 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1873 tokname[lasttoken], tokname[token]);
1875 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1882 synerror(const char *msg)
1885 outfmt(out2, "%s: %d: ", commandname, startlinno);
1886 outfmt(out2, "Syntax error: %s\n", msg);
1887 error((char *)NULL);
1891 setprompt(int which)
1893 whichprompt = which;
1899 out2str(getprompt(NULL));
1905 * called by editline -- any expansions to the prompt
1906 * should be added here.
1909 getprompt(void *unused __unused)
1911 static char ps[PROMPTLEN];
1915 static char internal_error[] = "??";
1918 * Select prompt format.
1920 switch (whichprompt) {
1931 return internal_error;
1935 * Format prompt string.
1937 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1944 * \h specifies just the local hostname,
1945 * \H specifies fully-qualified hostname.
1950 gethostname(&ps[i], PROMPTLEN - i);
1951 /* Skip to end of hostname. */
1952 trim = (*fmt == 'h') ? '.' : '\0';
1953 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1958 * Working directory.
1960 * \W specifies just the final component,
1961 * \w specifies the entire path.
1965 pwd = lookupvar("PWD");
1969 *pwd == '/' && pwd[1] != '\0')
1970 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1973 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1974 /* Skip to end of path. */
1975 while (ps[i + 1] != '\0')
1982 * '$' for normal users, '#' for root.
1985 ps[i] = (geteuid() != 0) ? '$' : '#';
1996 * Emit unrecognized formats verbatim.
2011 expandstr(const char *ps)
2014 struct jmploc jmploc;
2015 struct jmploc *const savehandler = handler;
2016 const int saveprompt = doprompt;
2017 struct parsefile *const savetopfile = getcurrentfile();
2018 struct parser_temp *const saveparser_temp = parser_temp;
2019 const char *result = NULL;
2021 if (!setjmp(jmploc.loc)) {
2024 setinputstring(ps, 1);
2026 readtoken1(pgetc(), DQSYNTAX, "\n\n", 0);
2027 if (backquotelist != NULL)
2028 error("Command substitution not allowed here");
2032 n.narg.text = wordtext;
2033 n.narg.backquote = backquotelist;
2035 expandarg(&n, NULL, 0);
2036 result = stackblock();
2039 handler = savehandler;
2040 doprompt = saveprompt;
2041 popfilesupto(savetopfile);
2042 if (parser_temp != saveparser_temp) {
2043 parser_temp_free_all();
2044 parser_temp = saveparser_temp;
2046 if (result != NULL) {
2048 } else if (exception == EXINT)