2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/param.h>
52 #include "expand.h" /* defines rmescapes() */
64 #include "exec.h" /* to check for special builtins */
66 #include "myhistedit.h"
70 * Shell command parser.
75 /* values of checkkwd variable */
80 /* values returned by readtoken */
86 struct heredoc *next; /* next here document in list */
87 union node *here; /* redirection node */
88 char *eofmark; /* string indicating end of input */
89 int striptabs; /* if set, strip leading tabs */
93 struct parser_temp *next;
98 static struct heredoc *heredoclist; /* list of here documents to read */
99 static int doprompt; /* if set, prompt the user */
100 static int needprompt; /* true if interactive and at start of line */
101 static int lasttoken; /* last token read */
102 static int tokpushback; /* last token pushed back */
103 static char *wordtext; /* text of last word returned by readtoken */
105 static struct nodelist *backquotelist;
106 static union node *redirnode;
107 static struct heredoc *heredoc;
108 static int quoteflag; /* set if (part of) last token was quoted */
109 static int startlinno; /* line # where last token started */
110 static int funclinno; /* line # where the current function started */
111 static struct parser_temp *parser_temp;
113 #define NOEOFMARK ((const char *)&heredoclist)
116 static union node *list(int);
117 static union node *andor(void);
118 static union node *pipeline(void);
119 static union node *command(void);
120 static union node *simplecmd(union node **, union node *);
121 static union node *makename(void);
122 static union node *makebinary(int type, union node *n1, union node *n2);
123 static void parsefname(void);
124 static void parseheredoc(void);
125 static int peektoken(void);
126 static int readtoken(void);
127 static int xxreadtoken(void);
128 static int readtoken1(int, const char *, const char *, int);
129 static int noexpand(char *);
130 static void consumetoken(int);
131 static void synexpect(int) __dead2;
132 static void synerror(const char *) __dead2;
133 static void setprompt(int);
134 static int pgetc_linecont(void);
135 static void getusername(char *, size_t);
139 parser_temp_alloc(size_t len)
141 struct parser_temp *t;
144 t = ckmalloc(sizeof(*t));
146 t->next = parser_temp;
148 t->data = ckmalloc(len);
155 parser_temp_realloc(void *ptr, size_t len)
157 struct parser_temp *t;
162 error("bug: parser_temp_realloc misused");
163 t->data = ckrealloc(t->data, len);
170 parser_temp_free_upto(void *ptr)
172 struct parser_temp *t;
176 while (parser_temp != NULL && !done) {
178 parser_temp = t->next;
179 done = t->data == ptr;
185 error("bug: parser_temp_free_upto misused");
190 parser_temp_free_all(void)
192 struct parser_temp *t;
195 while (parser_temp != NULL) {
197 parser_temp = t->next;
206 * Read and parse a command. Returns NEOF on end of file. (NULL is a
207 * valid parse tree indicating a blank line.)
211 parsecmd(int interact)
215 /* This assumes the parser is not re-entered,
216 * which could happen if we add command substitution on PS1/PS2.
218 parser_temp_free_all();
240 * Read and parse words for wordexp.
241 * Returns a list of NARG nodes; NULL if there are no words.
246 union node *n, *first = NULL, **pnext;
249 /* This assumes the parser is not re-entered,
250 * which could happen if we add command substitution on PS1/PS2.
252 parser_temp_free_all();
261 while ((t = readtoken()) != TEOF) {
266 pnext = &n->narg.next;
275 union node *ntop, *n1, *n2, *n3;
278 checkkwd = CHKNL | CHKKWD | CHKALIAS;
279 if (!nlflag && tokendlist[peektoken()])
285 if (tok == TBACKGND) {
286 if (n2 != NULL && n2->type == NPIPE) {
287 n2->npipe.backgnd = 1;
288 } else if (n2 != NULL && n2->type == NREDIR) {
291 n3 = (union node *)stalloc(sizeof (struct nredir));
294 n3->nredir.redirect = NULL;
300 else if (n1 == NULL) {
301 n1 = makebinary(NSEMI, ntop, n2);
305 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
306 n1->nbinary.ch2 = n3;
319 } else if (tok == TEOF && nlflag) {
325 checkkwd = CHKNL | CHKKWD | CHKALIAS;
326 if (!nlflag && tokendlist[peektoken()])
333 pungetc(); /* push back EOF on input */
354 if ((t = readtoken()) == TAND) {
356 } else if (t == TOR) {
362 n = makebinary(t, n, pipeline());
371 union node *n1, *n2, *pipenode;
372 struct nodelist *lp, *prev;
376 checkkwd = CHKNL | CHKKWD | CHKALIAS;
377 TRACE(("pipeline: entered\n"));
378 while (readtoken() == TNOT)
382 if (readtoken() == TPIPE) {
383 pipenode = (union node *)stalloc(sizeof (struct npipe));
384 pipenode->type = NPIPE;
385 pipenode->npipe.backgnd = 0;
386 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
387 pipenode->npipe.cmdlist = lp;
391 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
392 checkkwd = CHKNL | CHKKWD | CHKALIAS;
400 } while (readtoken() == TPIPE);
406 n2 = (union node *)stalloc(sizeof (struct nnot));
420 union node *ap, **app;
421 union node *cp, **cpp;
422 union node *redir, **rpp;
426 checkkwd = CHKNL | CHKKWD | CHKALIAS;
432 /* Check for redirection which may precede command */
433 while (readtoken() == TREDIR) {
434 *rpp = n2 = redirnode;
435 rpp = &n2->nfile.next;
440 switch (readtoken()) {
442 n1 = (union node *)stalloc(sizeof (struct nif));
444 if ((n1->nif.test = list(0)) == NULL)
447 n1->nif.ifpart = list(0);
449 while (readtoken() == TELIF) {
450 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
451 n2 = n2->nif.elsepart;
453 if ((n2->nif.test = list(0)) == NULL)
456 n2->nif.ifpart = list(0);
458 if (lasttoken == TELSE)
459 n2->nif.elsepart = list(0);
461 n2->nif.elsepart = NULL;
465 checkkwd = CHKKWD | CHKALIAS;
470 if ((n1 = list(0)) == NULL)
473 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
475 checkkwd = CHKKWD | CHKALIAS;
478 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
479 synerror("Bad for loop variable");
480 n1 = (union node *)stalloc(sizeof (struct nfor));
482 n1->nfor.var = wordtext;
484 if (readtoken() == TWORD && !quoteflag &&
485 equal(wordtext, "in")) {
487 while (readtoken() == TWORD) {
490 app = &n2->narg.next;
494 if (lasttoken == TNL)
496 else if (lasttoken != TSEMI)
499 static char argvars[5] = {
500 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
502 n2 = (union node *)stalloc(sizeof (struct narg));
504 n2->narg.text = argvars;
505 n2->narg.backquote = NULL;
506 n2->narg.next = NULL;
509 * Newline or semicolon here is optional (but note
510 * that the original Bourne shell only allowed NL).
512 if (lasttoken != TSEMI)
515 checkkwd = CHKNL | CHKKWD | CHKALIAS;
516 if ((t = readtoken()) == TDO)
518 else if (t == TBEGIN)
522 n1->nfor.body = list(0);
524 checkkwd = CHKKWD | CHKALIAS;
527 n1 = (union node *)stalloc(sizeof (struct ncase));
530 n1->ncase.expr = makename();
532 if (readtoken() != TWORD || ! equal(wordtext, "in"))
533 synerror("expecting \"in\"");
534 cpp = &n1->ncase.cases;
535 checkkwd = CHKNL | CHKKWD, readtoken();
536 while (lasttoken != TESAC) {
537 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
539 app = &cp->nclist.pattern;
540 if (lasttoken == TLP)
543 *app = ap = makename();
544 checkkwd = CHKNL | CHKKWD;
545 if (readtoken() != TPIPE)
547 app = &ap->narg.next;
550 ap->narg.next = NULL;
551 if (lasttoken != TRP)
553 cp->nclist.body = list(0);
555 checkkwd = CHKNL | CHKKWD | CHKALIAS;
556 if ((t = readtoken()) != TESAC) {
559 else if (t == TFALLTHRU)
560 cp->type = NCLISTFALLTHRU;
563 checkkwd = CHKNL | CHKKWD, readtoken();
565 cpp = &cp->nclist.next;
568 checkkwd = CHKKWD | CHKALIAS;
571 n1 = (union node *)stalloc(sizeof (struct nredir));
572 n1->type = NSUBSHELL;
573 n1->nredir.n = list(0);
574 n1->nredir.redirect = NULL;
576 checkkwd = CHKKWD | CHKALIAS;
582 checkkwd = CHKKWD | CHKALIAS;
584 /* A simple command must have at least one redirection or word. */
599 n1 = simplecmd(rpp, redir);
605 /* Now check for redirection which may follow command */
606 while (readtoken() == TREDIR) {
607 *rpp = n2 = redirnode;
608 rpp = &n2->nfile.next;
615 n2 = (union node *)stalloc(sizeof (struct nredir));
620 n1->nredir.redirect = redir;
628 simplecmd(union node **rpp, union node *redir)
630 union node *args, **app;
631 union node **orig_rpp = rpp;
632 union node *n = NULL;
636 /* If we don't have any redirections already, then we must reset */
637 /* rpp to be the address of the local redir variable. */
644 * We save the incoming value, because we need this for shell
645 * functions. There can not be a redirect or an argument between
646 * the function name and the open parenthesis.
650 savecheckkwd = CHKALIAS;
653 checkkwd = savecheckkwd;
654 if (readtoken() == TWORD) {
658 if (savecheckkwd != 0 && !isassignment(wordtext))
660 } else if (lasttoken == TREDIR) {
661 *rpp = n = redirnode;
662 rpp = &n->nfile.next;
663 parsefname(); /* read name of redirection file */
664 } else if (lasttoken == TLP && app == &args->narg.next
665 && rpp == orig_rpp) {
666 /* We have a function */
670 * - Require plain text.
671 * - Functions with '/' cannot be called.
673 * - Reject ksh extended glob patterns.
675 if (!noexpand(n->narg.text) || quoteflag ||
676 strchr(n->narg.text, '/') ||
678 n->narg.text[strlen(n->narg.text) - 1]))
679 synerror("Bad function name");
680 rmescapes(n->narg.text);
681 if (find_builtin(n->narg.text, &special) >= 0 &&
683 synerror("Cannot override a special builtin with a function");
685 n->narg.next = command();
695 n = (union node *)stalloc(sizeof (struct ncmd));
698 n->ncmd.redirect = redir;
707 n = (union node *)stalloc(sizeof (struct narg));
710 n->narg.text = wordtext;
711 n->narg.backquote = backquotelist;
716 makebinary(int type, union node *n1, union node *n2)
720 n = (union node *)stalloc(sizeof (struct nbinary));
730 checkkwd |= CHKALIAS;
734 fixredir(union node *n, const char *text, int err)
736 TRACE(("Fix redir %s %d\n", text, err));
738 n->ndup.vname = NULL;
740 if (is_digit(text[0]) && text[1] == '\0')
741 n->ndup.dupfd = digit_val(text[0]);
742 else if (text[0] == '-' && text[1] == '\0')
747 synerror("Bad fd number");
749 n->ndup.vname = makename();
757 union node *n = redirnode;
760 if (n->type == NHERE) {
761 struct heredoc *here = heredoc;
766 TRACE(("Here document %d\n", n->type));
767 if (here->striptabs) {
768 while (*wordtext == '\t')
771 if (! noexpand(wordtext))
772 synerror("Illegal eof marker for << redirection");
774 here->eofmark = wordtext;
776 if (heredoclist == NULL)
779 for (p = heredoclist ; p->next ; p = p->next);
782 } else if (n->type == NTOFD || n->type == NFROMFD) {
783 fixredir(n, wordtext, 0);
785 n->nfile.fname = makename();
791 * Input any here documents.
797 struct heredoc *here;
800 while (heredoclist) {
802 heredoclist = here->next;
807 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
808 here->eofmark, here->striptabs);
810 here->here->nhere.doc = n;
830 int alreadyseen = tokpushback;
839 if (checkkwd & CHKNL) {
847 * check for keywords and aliases
849 if (t == TWORD && !quoteflag)
851 const char * const *pp;
853 if (checkkwd & CHKKWD)
854 for (pp = parsekwd; *pp; pp++) {
855 if (**pp == *wordtext && equal(*pp, wordtext))
857 lasttoken = t = pp - parsekwd + KWDOFFSET;
858 TRACE(("keyword %s recognized\n", tokname[t]));
862 if (checkkwd & CHKALIAS &&
863 (ap = lookupalias(wordtext, 1)) != NULL) {
864 pushstring(ap->val, strlen(ap->val), ap);
874 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
876 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
883 * Read the next input token.
884 * If the token is a word, we set backquotelist to the list of cmds in
885 * backquotes. We set quoteflag to true if any part of the word was
887 * If the token is TREDIR, then we set redirnode to a structure containing
889 * In all cases, the variable startlinno is set to the number of the line
890 * on which the token starts.
892 * [Change comment: here documents and internal procedures]
893 * [Readtoken shouldn't have any arguments. Perhaps we should make the
894 * word parsing code into a separate routine. In this case, readtoken
895 * doesn't need to have any internal procedures, but parseword does.
896 * We could also make parseoperator in essence the main routine, and
897 * have parseword (readtoken1?) handle both words and redirection.]
900 #define RETURN(token) return lasttoken = token
916 for (;;) { /* until token or start of word found */
922 while ((c = pgetc()) != '\n' && c != PEOF);
926 if (pgetc() == '\n') {
927 startlinno = ++plinno;
937 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
940 needprompt = doprompt;
945 if (pgetc_linecont() == '&')
950 if (pgetc_linecont() == '|')
955 c = pgetc_linecont();
972 #define MAXNEST_static 8
975 const char *syntax; /* *SYNTAX */
976 int parenlevel; /* levels of parentheses in arithmetic */
977 enum tokenstate_category
980 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
981 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
988 * Check to see whether we are at the end of the here document. When this
989 * is called, c is set to the first character of the next input line. If
990 * we are at the end of the here document, this routine sets the c to PEOF.
991 * The new value of c is returned.
995 checkend(int c, const char *eofmark, int striptabs)
1001 if (c == *eofmark) {
1005 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
1007 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
1011 needprompt = doprompt;
1015 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
1017 } else if (c == '\n' && *eofmark == '\0') {
1020 needprompt = doprompt;
1027 * Parse a redirection operator. The variable "out" points to a string
1028 * specifying the fd to be redirected. The variable "c" contains the
1029 * first character of the redirection operator.
1033 parseredir(char *out, int c)
1038 np = (union node *)stalloc(sizeof (struct nfile));
1041 c = pgetc_linecont();
1047 np->type = NCLOBBER;
1052 } else { /* c == '<' */
1054 c = pgetc_linecont();
1056 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1057 np = (union node *)stalloc(sizeof (struct nhere));
1061 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1063 if ((c = pgetc_linecont()) == '-') {
1064 heredoc->striptabs = 1;
1066 heredoc->striptabs = 0;
1069 } else if (c == '&')
1079 np->nfile.fd = digit_val(fd);
1084 * Called to parse command substitutions.
1088 parsebackq(char *out, struct nodelist **pbqlist,
1089 int oldstyle, int dblquote, int quoted)
1091 struct nodelist **nlpp;
1094 struct jmploc jmploc;
1095 struct jmploc *const savehandler = handler;
1098 const int bq_startlinno = plinno;
1099 char *volatile ostr = NULL;
1100 struct parsefile *const savetopfile = getcurrentfile();
1101 struct heredoc *const saveheredoclist = heredoclist;
1102 struct heredoc *here;
1105 if (setjmp(jmploc.loc)) {
1106 popfilesupto(savetopfile);
1111 heredoclist = saveheredoclist;
1112 handler = savehandler;
1113 if (exception == EXERROR) {
1114 startlinno = bq_startlinno;
1115 synerror("Error in command substitution");
1117 longjmp(handler->loc, 1);
1120 savelen = out - stackblock();
1122 str = ckmalloc(savelen);
1123 memcpy(str, stackblock(), savelen);
1129 /* We must read until the closing backquote, giving special
1130 treatment to some slashes, and then push the string and
1131 reread it as input, interpreting it normally. */
1137 STARTSTACKSTR(oout);
1143 CHECKSTRSPACE(2, oout);
1144 c = pgetc_linecont();
1150 if (c != '\\' && c != '`' && c != '$'
1151 && (!dblquote || c != '"'))
1152 USTPUTC('\\', oout);
1157 needprompt = doprompt;
1161 startlinno = plinno;
1162 synerror("EOF in backquote substitution");
1170 USTPUTC('\0', oout);
1171 olen = oout - stackblock();
1173 ostr = ckmalloc(olen);
1174 memcpy(ostr, stackblock(), olen);
1175 setinputstring(ostr, 1);
1180 nlpp = &(*nlpp)->next;
1181 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1182 (*nlpp)->next = NULL;
1185 saveprompt = doprompt;
1192 if (peektoken() != TEOF)
1194 doprompt = saveprompt;
1201 * Start reading from old file again, ignoring any pushed back
1202 * tokens left from the backquote parsing
1208 CHECKSTRSPACE(savelen + 1, out);
1211 memcpy(out, str, savelen);
1212 STADJUST(savelen, out);
1220 here = saveheredoclist;
1222 while (here->next != NULL)
1224 here->next = heredoclist;
1225 heredoclist = saveheredoclist;
1227 handler = savehandler;
1230 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1232 USTPUTC(CTLBACKQ, out);
1238 * Called to parse a backslash escape sequence inside $'...'.
1239 * The backslash has already been read.
1242 readcstyleesc(char *out)
1250 synerror("Unterminated quoted string");
1263 case 'a': v = '\a'; break;
1264 case 'b': v = '\b'; break;
1265 case 'e': v = '\033'; break;
1266 case 'f': v = '\f'; break;
1267 case 'n': v = '\n'; break;
1268 case 'r': v = '\r'; break;
1269 case 't': v = '\t'; break;
1270 case 'v': v = '\v'; break;
1275 if (c >= '0' && c <= '9')
1276 v = (v << 4) + c - '0';
1277 else if (c >= 'A' && c <= 'F')
1278 v = (v << 4) + c - 'A' + 10;
1279 else if (c >= 'a' && c <= 'f')
1280 v = (v << 4) + c - 'a' + 10;
1286 case '0': case '1': case '2': case '3':
1287 case '4': case '5': case '6': case '7':
1290 if (c >= '0' && c <= '7') {
1294 if (c >= '0' && c <= '7') {
1304 if (c < 0x3f || c > 0x7a || c == 0x60)
1305 synerror("Bad escape sequence");
1306 if (c == '\\' && pgetc() != '\\')
1307 synerror("Bad escape sequence");
1315 n = c == 'U' ? 8 : 4;
1317 for (i = 0; i < n; i++) {
1319 if (c >= '0' && c <= '9')
1320 v = (v << 4) + c - '0';
1321 else if (c >= 'A' && c <= 'F')
1322 v = (v << 4) + c - 'A' + 10;
1323 else if (c >= 'a' && c <= 'f')
1324 v = (v << 4) + c - 'a' + 10;
1326 synerror("Bad escape sequence");
1328 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1329 synerror("Bad escape sequence");
1330 /* We really need iconv here. */
1331 if (initial_localeisutf8 && v > 127) {
1332 CHECKSTRSPACE(4, out);
1334 * We cannot use wctomb() as the locale may have
1338 USTPUTC(0xc0 | v >> 6, out);
1339 USTPUTC(0x80 | (v & 0x3f), out);
1341 } else if (v <= 0xffff) {
1342 USTPUTC(0xe0 | v >> 12, out);
1343 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1344 USTPUTC(0x80 | (v & 0x3f), out);
1346 } else if (v <= 0x10ffff) {
1347 USTPUTC(0xf0 | v >> 18, out);
1348 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1349 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1350 USTPUTC(0x80 | (v & 0x3f), out);
1358 synerror("Bad escape sequence");
1362 * We can't handle NUL bytes.
1363 * POSIX says we should skip till the closing quote.
1366 while ((c = pgetc()) != '\'') {
1370 synerror("Unterminated quoted string");
1382 if (SQSYNTAX[vc] == CCTL)
1383 USTPUTC(CTLESC, out);
1390 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1391 * is not NULL, read a here document. In the latter case, eofmark is the
1392 * word which marks the end of the document and striptabs is true if
1393 * leading tabs should be stripped from the document. The argument firstc
1394 * is the first character of the input token or document.
1396 * Because C does not have internal subroutines, I have simulated them
1397 * using goto's to implement the subroutine linkage. The following macros
1398 * will run code that appears at the end of readtoken1.
1401 #define PARSESUB() {goto parsesub; parsesub_return:;}
1402 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1405 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1411 struct nodelist *bqlist;
1416 struct tokenstate state_static[MAXNEST_static];
1417 int maxnest = MAXNEST_static;
1418 struct tokenstate *state = state_static;
1421 startlinno = plinno;
1426 state[level].syntax = initialsyntax;
1427 state[level].parenlevel = 0;
1428 state[level].category = TSTATE_TOP;
1431 loop: { /* for each line, until end of word */
1432 if (eofmark && eofmark != NOEOFMARK)
1433 /* set c to PEOF if at end of here document */
1434 c = checkend(c, eofmark, striptabs);
1435 for (;;) { /* until end of line or end of word */
1436 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1438 synentry = state[level].syntax[c];
1441 case CNL: /* '\n' */
1443 goto endword; /* exit outer loop */
1453 goto loop; /* continue outer loop */
1456 out = readcstyleesc(out);
1464 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1465 USTPUTC(CTLESC, out);
1468 case CBACK: /* backslash */
1473 } else if (c == '\n') {
1480 if (state[level].syntax == DQSYNTAX &&
1481 c != '\\' && c != '`' && c != '$' &&
1482 (c != '"' || (eofmark != NULL &&
1483 newvarnest == 0)) &&
1484 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1486 if ((eofmark == NULL ||
1488 state[level].syntax == BASESYNTAX)
1489 USTPUTC(CTLQUOTEMARK, out);
1490 if (SQSYNTAX[c] == CCTL)
1491 USTPUTC(CTLESC, out);
1493 if ((eofmark == NULL ||
1495 state[level].syntax == BASESYNTAX &&
1496 state[level].category == TSTATE_VAR_OLD)
1497 USTPUTC(CTLQUOTEEND, out);
1502 USTPUTC(CTLQUOTEMARK, out);
1503 state[level].syntax = SQSYNTAX;
1507 USTPUTC(CTLQUOTEMARK, out);
1508 state[level].syntax = DQSYNTAX;
1511 if (eofmark != NULL && newvarnest == 0)
1514 if (state[level].category == TSTATE_VAR_OLD)
1515 USTPUTC(CTLQUOTEEND, out);
1516 state[level].syntax = BASESYNTAX;
1520 case CVAR: /* '$' */
1521 PARSESUB(); /* parse substitution */
1523 case CENDVAR: /* '}' */
1525 ((state[level].category == TSTATE_VAR_OLD &&
1526 state[level].syntax ==
1527 state[level - 1].syntax) ||
1528 (state[level].category == TSTATE_VAR_NEW &&
1529 state[level].syntax == BASESYNTAX))) {
1530 if (state[level].category == TSTATE_VAR_NEW)
1533 USTPUTC(CTLENDVAR, out);
1538 case CLP: /* '(' in arithmetic */
1539 state[level].parenlevel++;
1542 case CRP: /* ')' in arithmetic */
1543 if (state[level].parenlevel > 0) {
1545 --state[level].parenlevel;
1547 if (pgetc_linecont() == ')') {
1549 state[level].category == TSTATE_ARITH) {
1551 USTPUTC(CTLENDARI, out);
1557 * (don't 2nd guess - no error)
1564 case CBQUOTE: /* '`' */
1565 out = parsebackq(out, &bqlist, 1,
1566 state[level].syntax == DQSYNTAX &&
1567 (eofmark == NULL || newvarnest > 0),
1568 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1571 goto endword; /* exit outer loop */
1576 goto endword; /* exit outer loop */
1583 if (state[level].syntax == ARISYNTAX)
1584 synerror("Missing '))'");
1585 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1586 synerror("Unterminated quoted string");
1587 if (state[level].category == TSTATE_VAR_OLD ||
1588 state[level].category == TSTATE_VAR_NEW) {
1589 startlinno = plinno;
1590 synerror("Missing '}'");
1592 if (state != state_static)
1593 parser_temp_free_upto(state);
1595 len = out - stackblock();
1597 if (eofmark == NULL) {
1598 if ((c == '>' || c == '<')
1601 && (*out == '\0' || is_digit(*out))) {
1603 return lasttoken = TREDIR;
1609 backquotelist = bqlist;
1610 grabstackblock(len);
1612 return lasttoken = TWORD;
1613 /* end of readtoken routine */
1617 * Parse a substitution. At this point, we have read the dollar sign
1626 static const char types[] = "}-+?=";
1631 c = pgetc_linecont();
1632 if (c == '(') { /* $(command) or $((arith)) */
1633 if (pgetc_linecont() == '(') {
1637 out = parsebackq(out, &bqlist, 0,
1638 state[level].syntax == DQSYNTAX &&
1639 (eofmark == NULL || newvarnest > 0),
1640 state[level].syntax == DQSYNTAX ||
1641 state[level].syntax == ARISYNTAX);
1643 } else if (c == '{' || is_name(c) || is_special(c)) {
1644 USTPUTC(CTLVAR, out);
1645 typeloc = out - stackblock();
1646 USTPUTC(VSNORMAL, out);
1650 c = pgetc_linecont();
1654 if (!is_eof(c) && is_name(c)) {
1658 c = pgetc_linecont();
1660 } while (!is_eof(c) && is_in_name(c));
1662 strncmp(out - length, "LINENO", length) == 0) {
1663 /* Replace the variable name with the
1664 * current line number. */
1666 CHECKSTRSPACE(11, out);
1669 linno -= funclinno - 1;
1670 length = snprintf(out, 11, "%d", linno);
1676 } else if (is_digit(c)) {
1677 if (subtype != VSNORMAL) {
1680 c = pgetc_linecont();
1681 } while (is_digit(c));
1684 c = pgetc_linecont();
1686 } else if (is_special(c)) {
1688 c = pgetc_linecont();
1689 if (subtype == 0 && c1 == '#') {
1691 if (strchr(types, c) == NULL && c != ':' &&
1692 c != '#' && c != '%')
1695 c = pgetc_linecont();
1696 if (c1 != '}' && c == '}') {
1711 else if (c == '\n' || c == PEOF)
1712 synerror("Unexpected end of line in substitution");
1713 else if (BASESYNTAX[c] != CCTL)
1720 c = pgetc_linecont();
1723 p = strchr(types, c);
1725 if (c == '\n' || c == PEOF)
1726 synerror("Unexpected end of line in substitution");
1729 if (BASESYNTAX[c] != CCTL)
1733 subtype = p - types + VSNORMAL;
1739 subtype = c == '#' ? VSTRIMLEFT :
1741 c = pgetc_linecont();
1749 } else if (subtype != VSERROR) {
1750 if (subtype == VSLENGTH && c != '}')
1755 if (state[level].syntax == DQSYNTAX ||
1756 state[level].syntax == ARISYNTAX)
1758 *(stackblock() + typeloc) = subtype | flags;
1759 if (subtype != VSNORMAL) {
1760 if (level + 1 >= maxnest) {
1762 if (state == state_static) {
1763 state = parser_temp_alloc(
1764 maxnest * sizeof(*state));
1765 memcpy(state, state_static,
1766 MAXNEST_static * sizeof(*state));
1768 state = parser_temp_realloc(state,
1769 maxnest * sizeof(*state));
1772 state[level].parenlevel = 0;
1773 if (subtype == VSMINUS || subtype == VSPLUS ||
1774 subtype == VSQUESTION || subtype == VSASSIGN) {
1776 * For operators that were in the Bourne shell,
1777 * inherit the double-quote state.
1779 state[level].syntax = state[level - 1].syntax;
1780 state[level].category = TSTATE_VAR_OLD;
1783 * The other operators take a pattern,
1784 * so go to BASESYNTAX.
1785 * Also, ' and " are now special, even
1786 * in here documents.
1788 state[level].syntax = BASESYNTAX;
1789 state[level].category = TSTATE_VAR_NEW;
1793 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1794 /* $'cstylequotes' */
1795 USTPUTC(CTLQUOTEMARK, out);
1796 state[level].syntax = SQSYNTAX;
1802 goto parsesub_return;
1807 * Parse an arithmetic expansion (indicate start of one and set state)
1811 if (level + 1 >= maxnest) {
1813 if (state == state_static) {
1814 state = parser_temp_alloc(
1815 maxnest * sizeof(*state));
1816 memcpy(state, state_static,
1817 MAXNEST_static * sizeof(*state));
1819 state = parser_temp_realloc(state,
1820 maxnest * sizeof(*state));
1823 state[level].syntax = ARISYNTAX;
1824 state[level].parenlevel = 0;
1825 state[level].category = TSTATE_ARITH;
1826 USTPUTC(CTLARI, out);
1827 if (state[level - 1].syntax == DQSYNTAX)
1831 goto parsearith_return;
1834 } /* end of readtoken */
1838 * Returns true if the text contains nothing to expand (no dollar signs
1843 noexpand(char *text)
1849 while ((c = *p++) != '\0') {
1850 if ( c == CTLQUOTEMARK)
1854 else if (BASESYNTAX[(int)c] == CCTL)
1862 * Return true if the argument is a legal variable name (a letter or
1863 * underscore followed by zero or more letters, underscores, and digits).
1867 goodname(const char *name)
1875 if (! is_in_name(*p))
1883 isassignment(const char *p)
1891 else if (!is_in_name(*p))
1899 consumetoken(int token)
1901 if (readtoken() != token)
1907 * Called when an unexpected token is read during the parse. The argument
1908 * is the token that is expected, or -1 if more than one type of token can
1909 * occur at this point.
1913 synexpect(int token)
1918 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1919 tokname[lasttoken], tokname[token]);
1921 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1928 synerror(const char *msg)
1931 outfmt(out2, "%s: %d: ", commandname, startlinno);
1933 outfmt(out2, "%s: ", arg0);
1934 outfmt(out2, "Syntax error: %s\n", msg);
1935 error((char *)NULL);
1939 setprompt(int which)
1941 whichprompt = which;
1949 out2str(getprompt(NULL));
1955 pgetc_linecont(void)
1959 while ((c = pgetc_macro()) == '\\') {
1969 /* Allow the backslash to be pushed back. */
1970 pushstring("\\", 1, NULL);
1978 static struct passwd *
1987 return (getpwnam(login));
1992 getusername(char *name, size_t namelen)
1994 static char cached_name[MAXLOGNAME];
1998 if (cached_name[0] == '\0') {
2002 * Handle the case when there is more than one
2003 * login with the same UID, or when the login
2004 * returned by getlogin(2) does no longer match
2008 if (pw == NULL || pw->pw_uid != euid)
2009 pw = getpwuid(euid);
2012 strlcpy(cached_name, pw->pw_name,
2013 sizeof(cached_name));
2015 snprintf(cached_name, sizeof(cached_name),
2020 strlcpy(name, cached_name, namelen);
2025 * called by editline -- any expansions to the prompt
2026 * should be added here.
2029 getprompt(void *unused __unused)
2031 static char ps[PROMPTLEN];
2037 static char internal_error[] = "??";
2040 * Select prompt format.
2042 switch (whichprompt) {
2053 return internal_error;
2057 * Format prompt string.
2059 for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++)
2066 * \h specifies just the local hostname,
2067 * \H specifies fully-qualified hostname.
2072 gethostname(&ps[i], PROMPTLEN - i - 1);
2073 ps[PROMPTLEN - 1] = '\0';
2074 /* Skip to end of hostname. */
2075 trim = (*fmt == 'h') ? '.' : '\0';
2076 while ((ps[i] != '\0') && (ps[i] != trim))
2086 getusername(&ps[i], PROMPTLEN - i);
2087 /* Skip to end of username. */
2088 while (ps[i + 1] != '\0')
2093 * Working directory.
2095 * \W specifies just the final component,
2096 * \w specifies the entire path.
2100 pwd = lookupvar("PWD");
2101 if (pwd == NULL || *pwd == '\0')
2104 *pwd == '/' && pwd[1] != '\0')
2105 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2108 home = lookupvar("HOME");
2110 homelen = strlen(home);
2112 strcmp(home, "/") != 0 &&
2113 strncmp(pwd, home, homelen) == 0 &&
2114 (pwd[homelen] == '/' ||
2115 pwd[homelen] == '\0')) {
2116 strlcpy(&ps[i], "~",
2122 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2125 /* Skip to end of path. */
2126 while (ps[i + 1] != '\0')
2133 * '$' for normal users, '#' for root.
2136 ps[i] = (geteuid() != 0) ? '$' : '#';
2147 * Emit unrecognized formats verbatim.
2151 if (i < PROMPTLEN - 2)
2163 expandstr(const char *ps)
2166 struct jmploc jmploc;
2167 struct jmploc *const savehandler = handler;
2168 const int saveprompt = doprompt;
2169 struct parsefile *const savetopfile = getcurrentfile();
2170 struct parser_temp *const saveparser_temp = parser_temp;
2171 const char *result = NULL;
2173 if (!setjmp(jmploc.loc)) {
2176 setinputstring(ps, 1);
2178 readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
2179 if (backquotelist != NULL)
2180 error("Command substitution not allowed here");
2184 n.narg.text = wordtext;
2185 n.narg.backquote = backquotelist;
2187 expandarg(&n, NULL, 0);
2188 result = stackblock();
2191 handler = savehandler;
2192 doprompt = saveprompt;
2193 popfilesupto(savetopfile);
2194 if (parser_temp != saveparser_temp) {
2195 parser_temp_free_all();
2196 parser_temp = saveparser_temp;
2198 if (result != NULL) {
2200 } else if (exception == EXINT)