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.
71 /* values of checkkwd variable */
76 /* values returned by readtoken */
82 struct heredoc *next; /* next here document in list */
83 union node *here; /* redirection node */
84 char *eofmark; /* string indicating end of input */
85 int striptabs; /* if set, strip leading tabs */
89 struct parser_temp *next;
94 static struct heredoc *heredoclist; /* list of here documents to read */
95 static int doprompt; /* if set, prompt the user */
96 static int needprompt; /* true if interactive and at start of line */
97 static int lasttoken; /* last token read */
98 static int tokpushback; /* last token pushed back */
99 static char *wordtext; /* text of last word returned by readtoken */
101 static struct nodelist *backquotelist;
102 static union node *redirnode;
103 static struct heredoc *heredoc;
104 static int quoteflag; /* set if (part of) last token was quoted */
105 static int startlinno; /* line # where last token started */
106 static int funclinno; /* line # where the current function started */
107 static struct parser_temp *parser_temp;
110 static union node *list(int);
111 static union node *andor(void);
112 static union node *pipeline(void);
113 static union node *command(void);
114 static union node *simplecmd(union node **, union node *);
115 static union node *makename(void);
116 static union node *makebinary(int type, union node *n1, union node *n2);
117 static void parsefname(void);
118 static void parseheredoc(void);
119 static int peektoken(void);
120 static int readtoken(void);
121 static int xxreadtoken(void);
122 static int readtoken1(int, const char *, const char *, int);
123 static int noexpand(char *);
124 static void consumetoken(int);
125 static void synexpect(int) __dead2;
126 static void synerror(const char *) __dead2;
127 static void setprompt(int);
131 parser_temp_alloc(size_t len)
133 struct parser_temp *t;
136 t = ckmalloc(sizeof(*t));
138 t->next = parser_temp;
140 t->data = ckmalloc(len);
147 parser_temp_realloc(void *ptr, size_t len)
149 struct parser_temp *t;
154 error("bug: parser_temp_realloc misused");
155 t->data = ckrealloc(t->data, len);
162 parser_temp_free_upto(void *ptr)
164 struct parser_temp *t;
168 while (parser_temp != NULL && !done) {
170 parser_temp = t->next;
171 done = t->data == ptr;
177 error("bug: parser_temp_free_upto misused");
182 parser_temp_free_all(void)
184 struct parser_temp *t;
187 while (parser_temp != NULL) {
189 parser_temp = t->next;
198 * Read and parse a command. Returns NEOF on end of file. (NULL is a
199 * valid parse tree indicating a blank line.)
203 parsecmd(int interact)
207 /* This assumes the parser is not re-entered,
208 * which could happen if we add command substitution on PS1/PS2.
210 parser_temp_free_all();
234 union node *ntop, *n1, *n2, *n3;
237 checkkwd = CHKNL | CHKKWD | CHKALIAS;
238 if (!nlflag && tokendlist[peektoken()])
244 if (tok == TBACKGND) {
245 if (n2 != NULL && n2->type == NPIPE) {
246 n2->npipe.backgnd = 1;
247 } else if (n2 != NULL && n2->type == NREDIR) {
250 n3 = (union node *)stalloc(sizeof (struct nredir));
253 n3->nredir.redirect = NULL;
259 else if (n1 == NULL) {
260 n1 = makebinary(NSEMI, ntop, n2);
264 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
265 n1->nbinary.ch2 = n3;
278 } else if (tok == TEOF && nlflag) {
284 checkkwd = CHKNL | CHKKWD | CHKALIAS;
285 if (!nlflag && tokendlist[peektoken()])
292 pungetc(); /* push back EOF on input */
313 if ((t = readtoken()) == TAND) {
315 } else if (t == TOR) {
321 n = makebinary(t, n, pipeline());
330 union node *n1, *n2, *pipenode;
331 struct nodelist *lp, *prev;
335 checkkwd = CHKNL | CHKKWD | CHKALIAS;
336 TRACE(("pipeline: entered\n"));
337 while (readtoken() == TNOT)
341 if (readtoken() == TPIPE) {
342 pipenode = (union node *)stalloc(sizeof (struct npipe));
343 pipenode->type = NPIPE;
344 pipenode->npipe.backgnd = 0;
345 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
346 pipenode->npipe.cmdlist = lp;
350 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
351 checkkwd = CHKNL | CHKKWD | CHKALIAS;
359 } while (readtoken() == TPIPE);
365 n2 = (union node *)stalloc(sizeof (struct nnot));
379 union node *ap, **app;
380 union node *cp, **cpp;
381 union node *redir, **rpp;
385 checkkwd = CHKNL | CHKKWD | CHKALIAS;
391 /* Check for redirection which may precede command */
392 while (readtoken() == TREDIR) {
393 *rpp = n2 = redirnode;
394 rpp = &n2->nfile.next;
399 switch (readtoken()) {
401 n1 = (union node *)stalloc(sizeof (struct nif));
403 if ((n1->nif.test = list(0)) == NULL)
406 n1->nif.ifpart = list(0);
408 while (readtoken() == TELIF) {
409 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
410 n2 = n2->nif.elsepart;
412 if ((n2->nif.test = list(0)) == NULL)
415 n2->nif.ifpart = list(0);
417 if (lasttoken == TELSE)
418 n2->nif.elsepart = list(0);
420 n2->nif.elsepart = NULL;
424 checkkwd = CHKKWD | CHKALIAS;
429 if ((n1 = list(0)) == NULL)
432 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
434 checkkwd = CHKKWD | CHKALIAS;
437 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
438 synerror("Bad for loop variable");
439 n1 = (union node *)stalloc(sizeof (struct nfor));
441 n1->nfor.var = wordtext;
442 while (readtoken() == TNL)
444 if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
446 while (readtoken() == TWORD) {
449 app = &n2->narg.next;
453 if (lasttoken != TNL && lasttoken != TSEMI)
456 static char argvars[5] = {
457 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
459 n2 = (union node *)stalloc(sizeof (struct narg));
461 n2->narg.text = argvars;
462 n2->narg.backquote = NULL;
463 n2->narg.next = NULL;
466 * Newline or semicolon here is optional (but note
467 * that the original Bourne shell only allowed NL).
469 if (lasttoken != TNL && lasttoken != TSEMI)
472 checkkwd = CHKNL | CHKKWD | CHKALIAS;
473 if ((t = readtoken()) == TDO)
475 else if (t == TBEGIN)
479 n1->nfor.body = list(0);
481 checkkwd = CHKKWD | CHKALIAS;
484 n1 = (union node *)stalloc(sizeof (struct ncase));
487 n1->ncase.expr = makename();
488 while (readtoken() == TNL);
489 if (lasttoken != TWORD || ! equal(wordtext, "in"))
490 synerror("expecting \"in\"");
491 cpp = &n1->ncase.cases;
492 checkkwd = CHKNL | CHKKWD, readtoken();
493 while (lasttoken != TESAC) {
494 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
496 app = &cp->nclist.pattern;
497 if (lasttoken == TLP)
500 *app = ap = makename();
501 checkkwd = CHKNL | CHKKWD;
502 if (readtoken() != TPIPE)
504 app = &ap->narg.next;
507 ap->narg.next = NULL;
508 if (lasttoken != TRP)
510 cp->nclist.body = list(0);
512 checkkwd = CHKNL | CHKKWD | CHKALIAS;
513 if ((t = readtoken()) != TESAC) {
516 else if (t == TFALLTHRU)
517 cp->type = NCLISTFALLTHRU;
520 checkkwd = CHKNL | CHKKWD, readtoken();
522 cpp = &cp->nclist.next;
525 checkkwd = CHKKWD | CHKALIAS;
528 n1 = (union node *)stalloc(sizeof (struct nredir));
529 n1->type = NSUBSHELL;
530 n1->nredir.n = list(0);
531 n1->nredir.redirect = NULL;
533 checkkwd = CHKKWD | CHKALIAS;
539 checkkwd = CHKKWD | CHKALIAS;
541 /* A simple command must have at least one redirection or word. */
556 n1 = simplecmd(rpp, redir);
562 /* Now check for redirection which may follow command */
563 while (readtoken() == TREDIR) {
564 *rpp = n2 = redirnode;
565 rpp = &n2->nfile.next;
572 n2 = (union node *)stalloc(sizeof (struct nredir));
577 n1->nredir.redirect = redir;
585 simplecmd(union node **rpp, union node *redir)
587 union node *args, **app;
588 union node **orig_rpp = rpp;
589 union node *n = NULL;
593 /* If we don't have any redirections already, then we must reset */
594 /* rpp to be the address of the local redir variable. */
601 * We save the incoming value, because we need this for shell
602 * functions. There can not be a redirect or an argument between
603 * the function name and the open parenthesis.
607 savecheckkwd = CHKALIAS;
610 checkkwd = savecheckkwd;
611 if (readtoken() == TWORD) {
615 if (savecheckkwd != 0 && !isassignment(wordtext))
617 } else if (lasttoken == TREDIR) {
618 *rpp = n = redirnode;
619 rpp = &n->nfile.next;
620 parsefname(); /* read name of redirection file */
621 } else if (lasttoken == TLP && app == &args->narg.next
622 && rpp == orig_rpp) {
623 /* We have a function */
627 * - Require plain text.
628 * - Functions with '/' cannot be called.
630 * - Reject ksh extended glob patterns.
632 if (!noexpand(n->narg.text) || quoteflag ||
633 strchr(n->narg.text, '/') ||
635 n->narg.text[strlen(n->narg.text) - 1]))
636 synerror("Bad function name");
637 rmescapes(n->narg.text);
638 if (find_builtin(n->narg.text, &special) >= 0 &&
640 synerror("Cannot override a special builtin with a function");
642 n->narg.next = command();
652 n = (union node *)stalloc(sizeof (struct ncmd));
655 n->ncmd.redirect = redir;
664 n = (union node *)stalloc(sizeof (struct narg));
667 n->narg.text = wordtext;
668 n->narg.backquote = backquotelist;
673 makebinary(int type, union node *n1, union node *n2)
677 n = (union node *)stalloc(sizeof (struct nbinary));
687 checkkwd |= CHKALIAS;
691 fixredir(union node *n, const char *text, int err)
693 TRACE(("Fix redir %s %d\n", text, err));
695 n->ndup.vname = NULL;
697 if (is_digit(text[0]) && text[1] == '\0')
698 n->ndup.dupfd = digit_val(text[0]);
699 else if (text[0] == '-' && text[1] == '\0')
704 synerror("Bad fd number");
706 n->ndup.vname = makename();
714 union node *n = redirnode;
717 if (n->type == NHERE) {
718 struct heredoc *here = heredoc;
723 TRACE(("Here document %d\n", n->type));
724 if (here->striptabs) {
725 while (*wordtext == '\t')
728 if (! noexpand(wordtext))
729 synerror("Illegal eof marker for << redirection");
731 here->eofmark = wordtext;
733 if (heredoclist == NULL)
736 for (p = heredoclist ; p->next ; p = p->next);
739 } else if (n->type == NTOFD || n->type == NFROMFD) {
740 fixredir(n, wordtext, 0);
742 n->nfile.fname = makename();
748 * Input any here documents.
754 struct heredoc *here;
757 while (heredoclist) {
759 heredoclist = here->next;
764 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
765 here->eofmark, here->striptabs);
767 here->here->nhere.doc = n;
787 int alreadyseen = tokpushback;
796 if (checkkwd & CHKNL) {
804 * check for keywords and aliases
806 if (t == TWORD && !quoteflag)
808 const char * const *pp;
810 if (checkkwd & CHKKWD)
811 for (pp = parsekwd; *pp; pp++) {
812 if (**pp == *wordtext && equal(*pp, wordtext))
814 lasttoken = t = pp - parsekwd + KWDOFFSET;
815 TRACE(("keyword %s recognized\n", tokname[t]));
819 if (checkkwd & CHKALIAS &&
820 (ap = lookupalias(wordtext, 1)) != NULL) {
821 pushstring(ap->val, strlen(ap->val), ap);
831 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
833 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
840 * Read the next input token.
841 * If the token is a word, we set backquotelist to the list of cmds in
842 * backquotes. We set quoteflag to true if any part of the word was
844 * If the token is TREDIR, then we set redirnode to a structure containing
846 * In all cases, the variable startlinno is set to the number of the line
847 * on which the token starts.
849 * [Change comment: here documents and internal procedures]
850 * [Readtoken shouldn't have any arguments. Perhaps we should make the
851 * word parsing code into a separate routine. In this case, readtoken
852 * doesn't need to have any internal procedures, but parseword does.
853 * We could also make parseoperator in essence the main routine, and
854 * have parseword (readtoken1?) handle both words and redirection.]
857 #define RETURN(token) return lasttoken = token
873 for (;;) { /* until token or start of word found */
879 while ((c = pgetc()) != '\n' && c != PEOF);
883 if (pgetc() == '\n') {
884 startlinno = ++plinno;
894 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
897 needprompt = doprompt;
929 #define MAXNEST_static 8
932 const char *syntax; /* *SYNTAX */
933 int parenlevel; /* levels of parentheses in arithmetic */
934 enum tokenstate_category
937 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
938 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
945 * Check to see whether we are at the end of the here document. When this
946 * is called, c is set to the first character of the next input line. If
947 * we are at the end of the here document, this routine sets the c to PEOF.
948 * The new value of c is returned.
952 checkend(int c, const char *eofmark, int striptabs)
962 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
964 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
968 needprompt = doprompt;
972 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
980 * Called to parse command substitutions.
984 parsebackq(char *out, struct nodelist **pbqlist,
985 int oldstyle, int dblquote, int quoted)
987 struct nodelist **nlpp;
990 struct jmploc jmploc;
991 struct jmploc *const savehandler = handler;
994 const int bq_startlinno = plinno;
995 char *volatile ostr = NULL;
996 struct parsefile *const savetopfile = getcurrentfile();
997 struct heredoc *const saveheredoclist = heredoclist;
998 struct heredoc *here;
1001 if (setjmp(jmploc.loc)) {
1002 popfilesupto(savetopfile);
1007 heredoclist = saveheredoclist;
1008 handler = savehandler;
1009 if (exception == EXERROR) {
1010 startlinno = bq_startlinno;
1011 synerror("Error in command substitution");
1013 longjmp(handler->loc, 1);
1016 savelen = out - stackblock();
1018 str = ckmalloc(savelen);
1019 memcpy(str, stackblock(), savelen);
1025 /* We must read until the closing backquote, giving special
1026 treatment to some slashes, and then push the string and
1027 reread it as input, interpreting it normally. */
1033 STARTSTACKSTR(oout);
1039 CHECKSTRSPACE(2, oout);
1045 if ((c = pgetc()) == '\n') {
1052 * If eating a newline, avoid putting
1053 * the newline into the new character
1054 * stream (via the USTPUTC after the
1059 if (c != '\\' && c != '`' && c != '$'
1060 && (!dblquote || c != '"'))
1061 USTPUTC('\\', oout);
1066 needprompt = doprompt;
1070 startlinno = plinno;
1071 synerror("EOF in backquote substitution");
1079 USTPUTC('\0', oout);
1080 olen = oout - stackblock();
1082 ostr = ckmalloc(olen);
1083 memcpy(ostr, stackblock(), olen);
1084 setinputstring(ostr, 1);
1089 nlpp = &(*nlpp)->next;
1090 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1091 (*nlpp)->next = NULL;
1094 saveprompt = doprompt;
1101 if (peektoken() != TEOF)
1103 doprompt = saveprompt;
1110 * Start reading from old file again, ignoring any pushed back
1111 * tokens left from the backquote parsing
1117 CHECKSTRSPACE(savelen + 1, out);
1120 memcpy(out, str, savelen);
1121 STADJUST(savelen, out);
1129 here = saveheredoclist;
1131 while (here->next != NULL)
1133 here->next = heredoclist;
1134 heredoclist = saveheredoclist;
1136 handler = savehandler;
1139 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1141 USTPUTC(CTLBACKQ, out);
1147 * Called to parse a backslash escape sequence inside $'...'.
1148 * The backslash has already been read.
1151 readcstyleesc(char *out)
1158 synerror("Unterminated quoted string");
1171 case 'a': v = '\a'; break;
1172 case 'b': v = '\b'; break;
1173 case 'e': v = '\033'; break;
1174 case 'f': v = '\f'; break;
1175 case 'n': v = '\n'; break;
1176 case 'r': v = '\r'; break;
1177 case 't': v = '\t'; break;
1178 case 'v': v = '\v'; break;
1183 if (c >= '0' && c <= '9')
1184 v = (v << 4) + c - '0';
1185 else if (c >= 'A' && c <= 'F')
1186 v = (v << 4) + c - 'A' + 10;
1187 else if (c >= 'a' && c <= 'f')
1188 v = (v << 4) + c - 'a' + 10;
1194 case '0': case '1': case '2': case '3':
1195 case '4': case '5': case '6': case '7':
1198 if (c >= '0' && c <= '7') {
1202 if (c >= '0' && c <= '7') {
1212 if (c < 0x3f || c > 0x7a || c == 0x60)
1213 synerror("Bad escape sequence");
1214 if (c == '\\' && pgetc() != '\\')
1215 synerror("Bad escape sequence");
1223 n = c == 'U' ? 8 : 4;
1225 for (i = 0; i < n; i++) {
1227 if (c >= '0' && c <= '9')
1228 v = (v << 4) + c - '0';
1229 else if (c >= 'A' && c <= 'F')
1230 v = (v << 4) + c - 'A' + 10;
1231 else if (c >= 'a' && c <= 'f')
1232 v = (v << 4) + c - 'a' + 10;
1234 synerror("Bad escape sequence");
1236 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1237 synerror("Bad escape sequence");
1238 /* We really need iconv here. */
1239 if (initial_localeisutf8 && v > 127) {
1240 CHECKSTRSPACE(4, out);
1242 * We cannot use wctomb() as the locale may have
1246 USTPUTC(0xc0 | v >> 6, out);
1247 USTPUTC(0x80 | (v & 0x3f), out);
1249 } else if (v <= 0xffff) {
1250 USTPUTC(0xe0 | v >> 12, out);
1251 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1252 USTPUTC(0x80 | (v & 0x3f), out);
1254 } else if (v <= 0x10ffff) {
1255 USTPUTC(0xf0 | v >> 18, out);
1256 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1257 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1258 USTPUTC(0x80 | (v & 0x3f), out);
1266 synerror("Bad escape sequence");
1270 * We can't handle NUL bytes.
1271 * POSIX says we should skip till the closing quote.
1274 while ((c = pgetc()) != '\'') {
1278 synerror("Unterminated quoted string");
1290 if (SQSYNTAX[v] == CCTL)
1291 USTPUTC(CTLESC, out);
1298 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1299 * is not NULL, read a here document. In the latter case, eofmark is the
1300 * word which marks the end of the document and striptabs is true if
1301 * leading tabs should be stripped from the document. The argument firstc
1302 * is the first character of the input token or document.
1304 * Because C does not have internal subroutines, I have simulated them
1305 * using goto's to implement the subroutine linkage. The following macros
1306 * will run code that appears at the end of readtoken1.
1309 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
1310 #define PARSESUB() {goto parsesub; parsesub_return:;}
1311 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1314 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1320 struct nodelist *bqlist;
1325 struct tokenstate state_static[MAXNEST_static];
1326 int maxnest = MAXNEST_static;
1327 struct tokenstate *state = state_static;
1330 startlinno = plinno;
1335 state[level].syntax = initialsyntax;
1336 state[level].parenlevel = 0;
1337 state[level].category = TSTATE_TOP;
1340 loop: { /* for each line, until end of word */
1342 /* set c to PEOF if at end of here document */
1343 c = checkend(c, eofmark, striptabs);
1344 for (;;) { /* until end of line or end of word */
1345 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1347 synentry = state[level].syntax[c];
1350 case CNL: /* '\n' */
1351 if (state[level].syntax == BASESYNTAX)
1352 goto endword; /* exit outer loop */
1360 goto loop; /* continue outer loop */
1363 out = readcstyleesc(out);
1371 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1372 USTPUTC(CTLESC, out);
1375 case CBACK: /* backslash */
1380 } else if (c == '\n') {
1387 if (state[level].syntax == DQSYNTAX &&
1388 c != '\\' && c != '`' && c != '$' &&
1389 (c != '"' || (eofmark != NULL &&
1390 newvarnest == 0)) &&
1391 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1393 if ((eofmark == NULL ||
1395 state[level].syntax == BASESYNTAX)
1396 USTPUTC(CTLQUOTEMARK, out);
1397 if (SQSYNTAX[c] == CCTL)
1398 USTPUTC(CTLESC, out);
1400 if ((eofmark == NULL ||
1402 state[level].syntax == BASESYNTAX &&
1403 state[level].category == TSTATE_VAR_OLD)
1404 USTPUTC(CTLQUOTEEND, out);
1409 USTPUTC(CTLQUOTEMARK, out);
1410 state[level].syntax = SQSYNTAX;
1414 USTPUTC(CTLQUOTEMARK, out);
1415 state[level].syntax = DQSYNTAX;
1418 if (eofmark != NULL && newvarnest == 0)
1421 if (state[level].category == TSTATE_VAR_OLD)
1422 USTPUTC(CTLQUOTEEND, out);
1423 state[level].syntax = BASESYNTAX;
1427 case CVAR: /* '$' */
1428 PARSESUB(); /* parse substitution */
1430 case CENDVAR: /* '}' */
1432 ((state[level].category == TSTATE_VAR_OLD &&
1433 state[level].syntax ==
1434 state[level - 1].syntax) ||
1435 (state[level].category == TSTATE_VAR_NEW &&
1436 state[level].syntax == BASESYNTAX))) {
1437 if (state[level].category == TSTATE_VAR_NEW)
1440 USTPUTC(CTLENDVAR, out);
1445 case CLP: /* '(' in arithmetic */
1446 state[level].parenlevel++;
1449 case CRP: /* ')' in arithmetic */
1450 if (state[level].parenlevel > 0) {
1452 --state[level].parenlevel;
1454 if (pgetc() == ')') {
1456 state[level].category == TSTATE_ARITH) {
1458 USTPUTC(CTLENDARI, out);
1464 * (don't 2nd guess - no error)
1471 case CBQUOTE: /* '`' */
1472 out = parsebackq(out, &bqlist, 1,
1473 state[level].syntax == DQSYNTAX &&
1474 (eofmark == NULL || newvarnest > 0),
1475 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1478 goto endword; /* exit outer loop */
1483 goto endword; /* exit outer loop */
1490 if (state[level].syntax == ARISYNTAX)
1491 synerror("Missing '))'");
1492 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1493 synerror("Unterminated quoted string");
1494 if (state[level].category == TSTATE_VAR_OLD ||
1495 state[level].category == TSTATE_VAR_NEW) {
1496 startlinno = plinno;
1497 synerror("Missing '}'");
1499 if (state != state_static)
1500 parser_temp_free_upto(state);
1502 len = out - stackblock();
1504 if (eofmark == NULL) {
1505 if ((c == '>' || c == '<')
1508 && (*out == '\0' || is_digit(*out))) {
1510 return lasttoken = TREDIR;
1516 backquotelist = bqlist;
1517 grabstackblock(len);
1519 return lasttoken = TWORD;
1520 /* end of readtoken routine */
1524 * Parse a redirection operator. The variable "out" points to a string
1525 * specifying the fd to be redirected. The variable "c" contains the
1526 * first character of the redirection operator.
1533 np = (union node *)stalloc(sizeof (struct nfile));
1542 np->type = NCLOBBER;
1547 } else { /* c == '<' */
1551 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1552 np = (union node *)stalloc(sizeof (struct nhere));
1556 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1558 if ((c = pgetc()) == '-') {
1559 heredoc->striptabs = 1;
1561 heredoc->striptabs = 0;
1564 } else if (c == '&')
1574 np->nfile.fd = digit_val(fd);
1576 goto parseredir_return;
1581 * Parse a substitution. At this point, we have read the dollar sign
1591 static const char types[] = "}-+?=";
1592 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1598 if (c == '(') { /* $(command) or $((arith)) */
1599 if (pgetc() == '(') {
1603 out = parsebackq(out, &bqlist, 0,
1604 state[level].syntax == DQSYNTAX &&
1605 (eofmark == NULL || newvarnest > 0),
1606 state[level].syntax == DQSYNTAX ||
1607 state[level].syntax == ARISYNTAX);
1609 } else if (c == '{' || is_name(c) || is_special(c)) {
1610 USTPUTC(CTLVAR, out);
1611 typeloc = out - stackblock();
1612 USTPUTC(VSNORMAL, out);
1621 if (!is_eof(c) && is_name(c)) {
1627 } while (!is_eof(c) && is_in_name(c));
1629 strncmp(out - length, "LINENO", length) == 0) {
1630 /* Replace the variable name with the
1631 * current line number. */
1634 linno -= funclinno - 1;
1635 snprintf(buf, sizeof(buf), "%d", linno);
1640 } else if (is_digit(c)) {
1641 if (bracketed_name) {
1645 } while (is_digit(c));
1650 } else if (is_special(c)) {
1653 if (subtype == 0 && c1 == '#') {
1655 if (strchr(types, c) == NULL && c != ':' &&
1656 c != '#' && c != '%')
1660 if (c1 != '}' && c == '}') {
1675 else if (c == '\n' || c == PEOF)
1676 synerror("Unexpected end of line in substitution");
1687 p = strchr(types, c);
1689 if (c == '\n' || c == PEOF)
1690 synerror("Unexpected end of line in substitution");
1696 subtype = p - types + VSNORMAL;
1702 subtype = c == '#' ? VSTRIMLEFT :
1712 } else if (subtype != VSERROR) {
1713 if (subtype == VSLENGTH && c != '}')
1718 if (state[level].syntax == DQSYNTAX ||
1719 state[level].syntax == ARISYNTAX)
1721 *(stackblock() + typeloc) = subtype | flags;
1722 if (subtype != VSNORMAL) {
1723 if (level + 1 >= maxnest) {
1725 if (state == state_static) {
1726 state = parser_temp_alloc(
1727 maxnest * sizeof(*state));
1728 memcpy(state, state_static,
1729 MAXNEST_static * sizeof(*state));
1731 state = parser_temp_realloc(state,
1732 maxnest * sizeof(*state));
1735 state[level].parenlevel = 0;
1736 if (subtype == VSMINUS || subtype == VSPLUS ||
1737 subtype == VSQUESTION || subtype == VSASSIGN) {
1739 * For operators that were in the Bourne shell,
1740 * inherit the double-quote state.
1742 state[level].syntax = state[level - 1].syntax;
1743 state[level].category = TSTATE_VAR_OLD;
1746 * The other operators take a pattern,
1747 * so go to BASESYNTAX.
1748 * Also, ' and " are now special, even
1749 * in here documents.
1751 state[level].syntax = BASESYNTAX;
1752 state[level].category = TSTATE_VAR_NEW;
1756 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1757 /* $'cstylequotes' */
1758 USTPUTC(CTLQUOTEMARK, out);
1759 state[level].syntax = SQSYNTAX;
1765 goto parsesub_return;
1770 * Parse an arithmetic expansion (indicate start of one and set state)
1774 if (level + 1 >= maxnest) {
1776 if (state == state_static) {
1777 state = parser_temp_alloc(
1778 maxnest * sizeof(*state));
1779 memcpy(state, state_static,
1780 MAXNEST_static * sizeof(*state));
1782 state = parser_temp_realloc(state,
1783 maxnest * sizeof(*state));
1786 state[level].syntax = ARISYNTAX;
1787 state[level].parenlevel = 0;
1788 state[level].category = TSTATE_ARITH;
1789 USTPUTC(CTLARI, out);
1790 if (state[level - 1].syntax == DQSYNTAX)
1794 goto parsearith_return;
1797 } /* end of readtoken */
1801 * Returns true if the text contains nothing to expand (no dollar signs
1806 noexpand(char *text)
1812 while ((c = *p++) != '\0') {
1813 if ( c == CTLQUOTEMARK)
1817 else if (BASESYNTAX[(int)c] == CCTL)
1825 * Return true if the argument is a legal variable name (a letter or
1826 * underscore followed by zero or more letters, underscores, and digits).
1830 goodname(const char *name)
1838 if (! is_in_name(*p))
1846 isassignment(const char *p)
1854 else if (!is_in_name(*p))
1862 consumetoken(int token)
1864 if (readtoken() != token)
1870 * Called when an unexpected token is read during the parse. The argument
1871 * is the token that is expected, or -1 if more than one type of token can
1872 * occur at this point.
1876 synexpect(int token)
1881 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1882 tokname[lasttoken], tokname[token]);
1884 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1891 synerror(const char *msg)
1894 outfmt(out2, "%s: %d: ", commandname, startlinno);
1895 outfmt(out2, "Syntax error: %s\n", msg);
1896 error((char *)NULL);
1900 setprompt(int which)
1902 whichprompt = which;
1908 out2str(getprompt(NULL));
1914 * called by editline -- any expansions to the prompt
1915 * should be added here.
1918 getprompt(void *unused __unused)
1920 static char ps[PROMPTLEN];
1924 static char internal_error[] = "??";
1927 * Select prompt format.
1929 switch (whichprompt) {
1940 return internal_error;
1944 * Format prompt string.
1946 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1953 * \h specifies just the local hostname,
1954 * \H specifies fully-qualified hostname.
1959 gethostname(&ps[i], PROMPTLEN - i);
1960 /* Skip to end of hostname. */
1961 trim = (*fmt == 'h') ? '.' : '\0';
1962 while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1967 * Working directory.
1969 * \W specifies just the final component,
1970 * \w specifies the entire path.
1974 pwd = lookupvar("PWD");
1978 *pwd == '/' && pwd[1] != '\0')
1979 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
1982 strlcpy(&ps[i], pwd, PROMPTLEN - i);
1983 /* Skip to end of path. */
1984 while (ps[i + 1] != '\0')
1991 * '$' for normal users, '#' for root.
1994 ps[i] = (geteuid() != 0) ? '$' : '#';
2005 * Emit unrecognized formats verbatim.
2020 expandstr(const char *ps)
2023 struct jmploc jmploc;
2024 struct jmploc *const savehandler = handler;
2025 const int saveprompt = doprompt;
2026 struct parsefile *const savetopfile = getcurrentfile();
2027 struct parser_temp *const saveparser_temp = parser_temp;
2028 const char *result = NULL;
2030 if (!setjmp(jmploc.loc)) {
2033 setinputstring(ps, 1);
2035 readtoken1(pgetc(), DQSYNTAX, "", 0);
2036 if (backquotelist != NULL)
2037 error("Command substitution not allowed here");
2041 n.narg.text = wordtext;
2042 n.narg.backquote = backquotelist;
2044 expandarg(&n, NULL, 0);
2045 result = stackblock();
2048 handler = savehandler;
2049 doprompt = saveprompt;
2050 popfilesupto(savetopfile);
2051 if (parser_temp != saveparser_temp) {
2052 parser_temp_free_all();
2053 parser_temp = saveparser_temp;
2055 if (result != NULL) {
2057 } else if (exception == EXINT)