]>
git.saurik.com Git - apple/shell_cmds.git/blob - sh/parser.c
3dc0d15a2e57f3306e1a6004fe54df03c9dc8f50
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: head/bin/sh/parser.c 301139 2016-06-01 16:56:29Z truckman $");
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
;
109 #define NOEOFMARK ((const char *)&heredoclist)
112 static union node
*list(int);
113 static union node
*andor(void);
114 static union node
*pipeline(void);
115 static union node
*command(void);
116 static union node
*simplecmd(union node
**, union node
*);
117 static union node
*makename(void);
118 static union node
*makebinary(int type
, union node
*n1
, union node
*n2
);
119 static void parsefname(void);
120 static void parseheredoc(void);
121 static int peektoken(void);
122 static int readtoken(void);
123 static int xxreadtoken(void);
124 static int readtoken1(int, const char *, const char *, int);
125 static int noexpand(char *);
126 static void consumetoken(int);
127 static void synexpect(int) __dead2
;
128 static void synerror(const char *) __dead2
;
129 static void setprompt(int);
130 static int pgetc_linecont(void);
134 parser_temp_alloc(size_t len
)
136 struct parser_temp
*t
;
139 t
= ckmalloc(sizeof(*t
));
141 t
->next
= parser_temp
;
143 t
->data
= ckmalloc(len
);
150 parser_temp_realloc(void *ptr
, size_t len
)
152 struct parser_temp
*t
;
157 error("bug: parser_temp_realloc misused");
158 t
->data
= ckrealloc(t
->data
, len
);
165 parser_temp_free_upto(void *ptr
)
167 struct parser_temp
*t
;
171 while (parser_temp
!= NULL
&& !done
) {
173 parser_temp
= t
->next
;
174 done
= t
->data
== ptr
;
180 error("bug: parser_temp_free_upto misused");
185 parser_temp_free_all(void)
187 struct parser_temp
*t
;
190 while (parser_temp
!= NULL
) {
192 parser_temp
= t
->next
;
201 * Read and parse a command. Returns NEOF on end of file. (NULL is a
202 * valid parse tree indicating a blank line.)
206 parsecmd(int interact
)
210 /* This assumes the parser is not re-entered,
211 * which could happen if we add command substitution on PS1/PS2.
213 parser_temp_free_all();
235 * Read and parse words for wordexp.
236 * Returns a list of NARG nodes; NULL if there are no words.
241 union node
*n
, *first
= NULL
, **pnext
;
244 /* This assumes the parser is not re-entered,
245 * which could happen if we add command substitution on PS1/PS2.
247 parser_temp_free_all();
256 while ((t
= readtoken()) != TEOF
) {
261 pnext
= &n
->narg
.next
;
270 union node
*ntop
, *n1
, *n2
, *n3
;
273 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
274 if (!nlflag
&& tokendlist
[peektoken()])
280 if (tok
== TBACKGND
) {
281 if (n2
!= NULL
&& n2
->type
== NPIPE
) {
282 n2
->npipe
.backgnd
= 1;
283 } else if (n2
!= NULL
&& n2
->type
== NREDIR
) {
286 n3
= (union node
*)stalloc(sizeof (struct nredir
));
289 n3
->nredir
.redirect
= NULL
;
295 else if (n1
== NULL
) {
296 n1
= makebinary(NSEMI
, ntop
, n2
);
300 n3
= makebinary(NSEMI
, n1
->nbinary
.ch2
, n2
);
301 n1
->nbinary
.ch2
= n3
;
314 } else if (tok
== TEOF
&& nlflag
) {
320 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
321 if (!nlflag
&& tokendlist
[peektoken()])
328 pungetc(); /* push back EOF on input */
349 if ((t
= readtoken()) == TAND
) {
351 } else if (t
== TOR
) {
357 n
= makebinary(t
, n
, pipeline());
366 union node
*n1
, *n2
, *pipenode
;
367 struct nodelist
*lp
, *prev
;
371 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
372 TRACE(("pipeline: entered\n"));
373 while (readtoken() == TNOT
)
377 if (readtoken() == TPIPE
) {
378 pipenode
= (union node
*)stalloc(sizeof (struct npipe
));
379 pipenode
->type
= NPIPE
;
380 pipenode
->npipe
.backgnd
= 0;
381 lp
= (struct nodelist
*)stalloc(sizeof (struct nodelist
));
382 pipenode
->npipe
.cmdlist
= lp
;
386 lp
= (struct nodelist
*)stalloc(sizeof (struct nodelist
));
387 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
395 } while (readtoken() == TPIPE
);
401 n2
= (union node
*)stalloc(sizeof (struct nnot
));
415 union node
*ap
, **app
;
416 union node
*cp
, **cpp
;
417 union node
*redir
, **rpp
;
421 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
427 /* Check for redirection which may precede command */
428 while (readtoken() == TREDIR
) {
429 *rpp
= n2
= redirnode
;
430 rpp
= &n2
->nfile
.next
;
435 switch (readtoken()) {
437 n1
= (union node
*)stalloc(sizeof (struct nif
));
439 if ((n1
->nif
.test
= list(0)) == NULL
)
442 n1
->nif
.ifpart
= list(0);
444 while (readtoken() == TELIF
) {
445 n2
->nif
.elsepart
= (union node
*)stalloc(sizeof (struct nif
));
446 n2
= n2
->nif
.elsepart
;
448 if ((n2
->nif
.test
= list(0)) == NULL
)
451 n2
->nif
.ifpart
= list(0);
453 if (lasttoken
== TELSE
)
454 n2
->nif
.elsepart
= list(0);
456 n2
->nif
.elsepart
= NULL
;
460 checkkwd
= CHKKWD
| CHKALIAS
;
465 if ((n1
= list(0)) == NULL
)
468 n1
= makebinary((t
== TWHILE
)? NWHILE
: NUNTIL
, n1
, list(0));
470 checkkwd
= CHKKWD
| CHKALIAS
;
473 if (readtoken() != TWORD
|| quoteflag
|| ! goodname(wordtext
))
474 synerror("Bad for loop variable");
475 n1
= (union node
*)stalloc(sizeof (struct nfor
));
477 n1
->nfor
.var
= wordtext
;
478 while (readtoken() == TNL
)
480 if (lasttoken
== TWORD
&& ! quoteflag
&& equal(wordtext
, "in")) {
482 while (readtoken() == TWORD
) {
485 app
= &n2
->narg
.next
;
489 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
492 static char argvars
[5] = {
493 CTLVAR
, VSNORMAL
|VSQUOTE
, '@', '=', '\0'
495 n2
= (union node
*)stalloc(sizeof (struct narg
));
497 n2
->narg
.text
= argvars
;
498 n2
->narg
.backquote
= NULL
;
499 n2
->narg
.next
= NULL
;
502 * Newline or semicolon here is optional (but note
503 * that the original Bourne shell only allowed NL).
505 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
508 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
509 if ((t
= readtoken()) == TDO
)
511 else if (t
== TBEGIN
)
515 n1
->nfor
.body
= list(0);
517 checkkwd
= CHKKWD
| CHKALIAS
;
520 n1
= (union node
*)stalloc(sizeof (struct ncase
));
523 n1
->ncase
.expr
= makename();
524 while (readtoken() == TNL
);
525 if (lasttoken
!= TWORD
|| ! equal(wordtext
, "in"))
526 synerror("expecting \"in\"");
527 cpp
= &n1
->ncase
.cases
;
528 checkkwd
= CHKNL
| CHKKWD
, readtoken();
529 while (lasttoken
!= TESAC
) {
530 *cpp
= cp
= (union node
*)stalloc(sizeof (struct nclist
));
532 app
= &cp
->nclist
.pattern
;
533 if (lasttoken
== TLP
)
536 *app
= ap
= makename();
537 checkkwd
= CHKNL
| CHKKWD
;
538 if (readtoken() != TPIPE
)
540 app
= &ap
->narg
.next
;
543 ap
->narg
.next
= NULL
;
544 if (lasttoken
!= TRP
)
546 cp
->nclist
.body
= list(0);
548 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
549 if ((t
= readtoken()) != TESAC
) {
552 else if (t
== TFALLTHRU
)
553 cp
->type
= NCLISTFALLTHRU
;
556 checkkwd
= CHKNL
| CHKKWD
, readtoken();
558 cpp
= &cp
->nclist
.next
;
561 checkkwd
= CHKKWD
| CHKALIAS
;
564 n1
= (union node
*)stalloc(sizeof (struct nredir
));
565 n1
->type
= NSUBSHELL
;
566 n1
->nredir
.n
= list(0);
567 n1
->nredir
.redirect
= NULL
;
569 checkkwd
= CHKKWD
| CHKALIAS
;
575 checkkwd
= CHKKWD
| CHKALIAS
;
577 /* A simple command must have at least one redirection or word. */
592 n1
= simplecmd(rpp
, redir
);
598 /* Now check for redirection which may follow command */
599 while (readtoken() == TREDIR
) {
600 *rpp
= n2
= redirnode
;
601 rpp
= &n2
->nfile
.next
;
608 n2
= (union node
*)stalloc(sizeof (struct nredir
));
613 n1
->nredir
.redirect
= redir
;
621 simplecmd(union node
**rpp
, union node
*redir
)
623 union node
*args
, **app
;
624 union node
**orig_rpp
= rpp
;
625 union node
*n
= NULL
;
629 /* If we don't have any redirections already, then we must reset */
630 /* rpp to be the address of the local redir variable. */
637 * We save the incoming value, because we need this for shell
638 * functions. There can not be a redirect or an argument between
639 * the function name and the open parenthesis.
643 savecheckkwd
= CHKALIAS
;
646 checkkwd
= savecheckkwd
;
647 if (readtoken() == TWORD
) {
651 if (savecheckkwd
!= 0 && !isassignment(wordtext
))
653 } else if (lasttoken
== TREDIR
) {
654 *rpp
= n
= redirnode
;
655 rpp
= &n
->nfile
.next
;
656 parsefname(); /* read name of redirection file */
657 } else if (lasttoken
== TLP
&& app
== &args
->narg
.next
658 && rpp
== orig_rpp
) {
659 /* We have a function */
663 * - Require plain text.
664 * - Functions with '/' cannot be called.
666 * - Reject ksh extended glob patterns.
668 if (!noexpand(n
->narg
.text
) || quoteflag
||
669 strchr(n
->narg
.text
, '/') ||
671 n
->narg
.text
[strlen(n
->narg
.text
) - 1]))
672 synerror("Bad function name");
673 rmescapes(n
->narg
.text
);
674 if (find_builtin(n
->narg
.text
, &special
) >= 0 &&
676 synerror("Cannot override a special builtin with a function");
678 n
->narg
.next
= command();
688 n
= (union node
*)stalloc(sizeof (struct ncmd
));
691 n
->ncmd
.redirect
= redir
;
700 n
= (union node
*)stalloc(sizeof (struct narg
));
703 n
->narg
.text
= wordtext
;
704 n
->narg
.backquote
= backquotelist
;
709 makebinary(int type
, union node
*n1
, union node
*n2
)
713 n
= (union node
*)stalloc(sizeof (struct nbinary
));
723 checkkwd
|= CHKALIAS
;
727 fixredir(union node
*n
, const char *text
, int err
)
729 TRACE(("Fix redir %s %d\n", text
, err
));
731 n
->ndup
.vname
= NULL
;
733 if (is_digit(text
[0]) && text
[1] == '\0')
734 n
->ndup
.dupfd
= digit_val(text
[0]);
735 else if (text
[0] == '-' && text
[1] == '\0')
740 synerror("Bad fd number");
742 n
->ndup
.vname
= makename();
750 union node
*n
= redirnode
;
753 if (n
->type
== NHERE
) {
754 struct heredoc
*here
= heredoc
;
759 TRACE(("Here document %d\n", n
->type
));
760 if (here
->striptabs
) {
761 while (*wordtext
== '\t')
764 if (! noexpand(wordtext
))
765 synerror("Illegal eof marker for << redirection");
767 here
->eofmark
= wordtext
;
769 if (heredoclist
== NULL
)
772 for (p
= heredoclist
; p
->next
; p
= p
->next
);
775 } else if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
776 fixredir(n
, wordtext
, 0);
778 n
->nfile
.fname
= makename();
784 * Input any here documents.
790 struct heredoc
*here
;
793 while (heredoclist
) {
795 heredoclist
= here
->next
;
800 readtoken1(pgetc(), here
->here
->type
== NHERE
? SQSYNTAX
: DQSYNTAX
,
801 here
->eofmark
, here
->striptabs
);
803 here
->here
->nhere
.doc
= n
;
823 int alreadyseen
= tokpushback
;
832 if (checkkwd
& CHKNL
) {
840 * check for keywords and aliases
842 if (t
== TWORD
&& !quoteflag
)
844 const char * const *pp
;
846 if (checkkwd
& CHKKWD
)
847 for (pp
= parsekwd
; *pp
; pp
++) {
848 if (**pp
== *wordtext
&& equal(*pp
, wordtext
))
850 lasttoken
= t
= pp
- parsekwd
+ KWDOFFSET
;
851 TRACE(("keyword %s recognized\n", tokname
[t
]));
855 if (checkkwd
& CHKALIAS
&&
856 (ap
= lookupalias(wordtext
, 1)) != NULL
) {
857 pushstring(ap
->val
, strlen(ap
->val
), ap
);
867 TRACE(("token %s %s\n", tokname
[t
], t
== TWORD
? wordtext
: ""));
869 TRACE(("reread token %s %s\n", tokname
[t
], t
== TWORD
? wordtext
: ""));
876 * Read the next input token.
877 * If the token is a word, we set backquotelist to the list of cmds in
878 * backquotes. We set quoteflag to true if any part of the word was
880 * If the token is TREDIR, then we set redirnode to a structure containing
882 * In all cases, the variable startlinno is set to the number of the line
883 * on which the token starts.
885 * [Change comment: here documents and internal procedures]
886 * [Readtoken shouldn't have any arguments. Perhaps we should make the
887 * word parsing code into a separate routine. In this case, readtoken
888 * doesn't need to have any internal procedures, but parseword does.
889 * We could also make parseoperator in essence the main routine, and
890 * have parseword (readtoken1?) handle both words and redirection.]
893 #define RETURN(token) return lasttoken = token
909 for (;;) { /* until token or start of word found */
915 while ((c
= pgetc()) != '\n' && c
!= PEOF
);
919 if (pgetc() == '\n') {
920 startlinno
= ++plinno
;
930 return readtoken1(c
, BASESYNTAX
, (char *)NULL
, 0);
933 needprompt
= doprompt
;
938 if (pgetc_linecont() == '&')
943 if (pgetc_linecont() == '|')
948 c
= pgetc_linecont();
965 #define MAXNEST_static 8
968 const char *syntax
; /* *SYNTAX */
969 int parenlevel
; /* levels of parentheses in arithmetic */
970 enum tokenstate_category
973 TSTATE_VAR_OLD
, /* ${var+-=?}, inherits dquotes */
974 TSTATE_VAR_NEW
, /* other ${var...}, own dquote state */
981 * Check to see whether we are at the end of the here document. When this
982 * is called, c is set to the first character of the next input line. If
983 * we are at the end of the here document, this routine sets the c to PEOF.
984 * The new value of c is returned.
988 checkend(int c
, const char *eofmark
, int striptabs
)
998 for (q
= eofmark
+ 1; c2
= pgetc(), *q
!= '\0' && c2
== *q
; q
++)
1000 if ((c2
== PEOF
|| c2
== '\n') && *q
== '\0') {
1004 needprompt
= doprompt
;
1008 pushstring(eofmark
+ 1, q
- (eofmark
+ 1), NULL
);
1010 } else if (c
== '\n' && *eofmark
== '\0') {
1013 needprompt
= doprompt
;
1020 * Parse a redirection operator. The variable "out" points to a string
1021 * specifying the fd to be redirected. The variable "c" contains the
1022 * first character of the redirection operator.
1026 parseredir(char *out
, int c
)
1031 np
= (union node
*)stalloc(sizeof (struct nfile
));
1034 c
= pgetc_linecont();
1040 np
->type
= NCLOBBER
;
1045 } else { /* c == '<' */
1047 c
= pgetc_linecont();
1049 if (sizeof (struct nfile
) != sizeof (struct nhere
)) {
1050 np
= (union node
*)stalloc(sizeof (struct nhere
));
1054 heredoc
= (struct heredoc
*)stalloc(sizeof (struct heredoc
));
1056 if ((c
= pgetc_linecont()) == '-') {
1057 heredoc
->striptabs
= 1;
1059 heredoc
->striptabs
= 0;
1062 } else if (c
== '&')
1072 np
->nfile
.fd
= digit_val(fd
);
1077 * Called to parse command substitutions.
1081 parsebackq(char *out
, struct nodelist
**pbqlist
,
1082 int oldstyle
, int dblquote
, int quoted
)
1084 struct nodelist
**nlpp
;
1087 struct jmploc jmploc
;
1088 struct jmploc
*const savehandler
= handler
;
1091 const int bq_startlinno
= plinno
;
1092 char *volatile ostr
= NULL
;
1093 struct parsefile
*const savetopfile
= getcurrentfile();
1094 struct heredoc
*const saveheredoclist
= heredoclist
;
1095 struct heredoc
*here
;
1098 if (setjmp(jmploc
.loc
)) {
1099 popfilesupto(savetopfile
);
1104 heredoclist
= saveheredoclist
;
1105 handler
= savehandler
;
1106 if (exception
== EXERROR
) {
1107 startlinno
= bq_startlinno
;
1108 synerror("Error in command substitution");
1110 longjmp(handler
->loc
, 1);
1113 savelen
= out
- stackblock();
1115 str
= ckmalloc(savelen
);
1116 memcpy(str
, stackblock(), savelen
);
1122 /* We must read until the closing backquote, giving special
1123 treatment to some slashes, and then push the string and
1124 reread it as input, interpreting it normally. */
1130 STARTSTACKSTR(oout
);
1136 CHECKSTRSPACE(2, oout
);
1137 c
= pgetc_linecont();
1143 if (c
!= '\\' && c
!= '`' && c
!= '$'
1144 && (!dblquote
|| c
!= '"'))
1145 USTPUTC('\\', oout
);
1150 needprompt
= doprompt
;
1154 startlinno
= plinno
;
1155 synerror("EOF in backquote substitution");
1163 USTPUTC('\0', oout
);
1164 olen
= oout
- stackblock();
1166 ostr
= ckmalloc(olen
);
1167 memcpy(ostr
, stackblock(), olen
);
1168 setinputstring(ostr
, 1);
1173 nlpp
= &(*nlpp
)->next
;
1174 *nlpp
= (struct nodelist
*)stalloc(sizeof (struct nodelist
));
1175 (*nlpp
)->next
= NULL
;
1178 saveprompt
= doprompt
;
1185 if (peektoken() != TEOF
)
1187 doprompt
= saveprompt
;
1194 * Start reading from old file again, ignoring any pushed back
1195 * tokens left from the backquote parsing
1201 CHECKSTRSPACE(savelen
+ 1, out
);
1204 memcpy(out
, str
, savelen
);
1205 STADJUST(savelen
, out
);
1213 here
= saveheredoclist
;
1215 while (here
->next
!= NULL
)
1217 here
->next
= heredoclist
;
1218 heredoclist
= saveheredoclist
;
1220 handler
= savehandler
;
1223 USTPUTC(CTLBACKQ
| CTLQUOTE
, out
);
1225 USTPUTC(CTLBACKQ
, out
);
1231 * Called to parse a backslash escape sequence inside $'...'.
1232 * The backslash has already been read.
1235 readcstyleesc(char *out
)
1243 synerror("Unterminated quoted string");
1256 case 'a': v
= '\a'; break;
1257 case 'b': v
= '\b'; break;
1258 case 'e': v
= '\033'; break;
1259 case 'f': v
= '\f'; break;
1260 case 'n': v
= '\n'; break;
1261 case 'r': v
= '\r'; break;
1262 case 't': v
= '\t'; break;
1263 case 'v': v
= '\v'; break;
1268 if (c
>= '0' && c
<= '9')
1269 v
= (v
<< 4) + c
- '0';
1270 else if (c
>= 'A' && c
<= 'F')
1271 v
= (v
<< 4) + c
- 'A' + 10;
1272 else if (c
>= 'a' && c
<= 'f')
1273 v
= (v
<< 4) + c
- 'a' + 10;
1279 case '0': case '1': case '2': case '3':
1280 case '4': case '5': case '6': case '7':
1283 if (c
>= '0' && c
<= '7') {
1287 if (c
>= '0' && c
<= '7') {
1297 if (c
< 0x3f || c
> 0x7a || c
== 0x60)
1298 synerror("Bad escape sequence");
1299 if (c
== '\\' && pgetc() != '\\')
1300 synerror("Bad escape sequence");
1308 n
= c
== 'U' ? 8 : 4;
1310 for (i
= 0; i
< n
; i
++) {
1312 if (c
>= '0' && c
<= '9')
1313 v
= (v
<< 4) + c
- '0';
1314 else if (c
>= 'A' && c
<= 'F')
1315 v
= (v
<< 4) + c
- 'A' + 10;
1316 else if (c
>= 'a' && c
<= 'f')
1317 v
= (v
<< 4) + c
- 'a' + 10;
1319 synerror("Bad escape sequence");
1321 if (v
== 0 || (v
>= 0xd800 && v
<= 0xdfff))
1322 synerror("Bad escape sequence");
1323 /* We really need iconv here. */
1324 if (initial_localeisutf8
&& v
> 127) {
1325 CHECKSTRSPACE(4, out
);
1327 * We cannot use wctomb() as the locale may have
1331 USTPUTC(0xc0 | v
>> 6, out
);
1332 USTPUTC(0x80 | (v
& 0x3f), out
);
1334 } else if (v
<= 0xffff) {
1335 USTPUTC(0xe0 | v
>> 12, out
);
1336 USTPUTC(0x80 | ((v
>> 6) & 0x3f), out
);
1337 USTPUTC(0x80 | (v
& 0x3f), out
);
1339 } else if (v
<= 0x10ffff) {
1340 USTPUTC(0xf0 | v
>> 18, out
);
1341 USTPUTC(0x80 | ((v
>> 12) & 0x3f), out
);
1342 USTPUTC(0x80 | ((v
>> 6) & 0x3f), out
);
1343 USTPUTC(0x80 | (v
& 0x3f), out
);
1351 synerror("Bad escape sequence");
1355 * We can't handle NUL bytes.
1356 * POSIX says we should skip till the closing quote.
1359 while ((c
= pgetc()) != '\'') {
1363 synerror("Unterminated quoted string");
1375 if (SQSYNTAX
[vc
] == CCTL
)
1376 USTPUTC(CTLESC
, out
);
1383 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1384 * is not NULL, read a here document. In the latter case, eofmark is the
1385 * word which marks the end of the document and striptabs is true if
1386 * leading tabs should be stripped from the document. The argument firstc
1387 * is the first character of the input token or document.
1389 * Because C does not have internal subroutines, I have simulated them
1390 * using goto's to implement the subroutine linkage. The following macros
1391 * will run code that appears at the end of readtoken1.
1394 #define PARSESUB() {goto parsesub; parsesub_return:;}
1395 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1398 readtoken1(int firstc
, char const *initialsyntax
, const char *eofmark
,
1404 struct nodelist
*bqlist
;
1409 struct tokenstate state_static
[MAXNEST_static
];
1410 int maxnest
= MAXNEST_static
;
1411 struct tokenstate
*state
= state_static
;
1414 startlinno
= plinno
;
1419 state
[level
].syntax
= initialsyntax
;
1420 state
[level
].parenlevel
= 0;
1421 state
[level
].category
= TSTATE_TOP
;
1424 loop
: { /* for each line, until end of word */
1425 if (eofmark
&& eofmark
!= NOEOFMARK
)
1426 /* set c to PEOF if at end of here document */
1427 c
= checkend(c
, eofmark
, striptabs
);
1428 for (;;) { /* until end of line or end of word */
1429 CHECKSTRSPACE(4, out
); /* permit 4 calls to USTPUTC */
1431 synentry
= state
[level
].syntax
[c
];
1434 case CNL
: /* '\n' */
1435 if (state
[level
].syntax
== BASESYNTAX
)
1436 goto endword
; /* exit outer loop */
1444 goto loop
; /* continue outer loop */
1447 out
= readcstyleesc(out
);
1455 if (eofmark
== NULL
|| initialsyntax
!= SQSYNTAX
)
1456 USTPUTC(CTLESC
, out
);
1459 case CBACK
: /* backslash */
1464 } else if (c
== '\n') {
1471 if (state
[level
].syntax
== DQSYNTAX
&&
1472 c
!= '\\' && c
!= '`' && c
!= '$' &&
1473 (c
!= '"' || (eofmark
!= NULL
&&
1474 newvarnest
== 0)) &&
1475 (c
!= '}' || state
[level
].category
!= TSTATE_VAR_OLD
))
1477 if ((eofmark
== NULL
||
1479 state
[level
].syntax
== BASESYNTAX
)
1480 USTPUTC(CTLQUOTEMARK
, out
);
1481 if (SQSYNTAX
[c
] == CCTL
)
1482 USTPUTC(CTLESC
, out
);
1484 if ((eofmark
== NULL
||
1486 state
[level
].syntax
== BASESYNTAX
&&
1487 state
[level
].category
== TSTATE_VAR_OLD
)
1488 USTPUTC(CTLQUOTEEND
, out
);
1493 USTPUTC(CTLQUOTEMARK
, out
);
1494 state
[level
].syntax
= SQSYNTAX
;
1498 USTPUTC(CTLQUOTEMARK
, out
);
1499 state
[level
].syntax
= DQSYNTAX
;
1502 if (eofmark
!= NULL
&& newvarnest
== 0)
1505 if (state
[level
].category
== TSTATE_VAR_OLD
)
1506 USTPUTC(CTLQUOTEEND
, out
);
1507 state
[level
].syntax
= BASESYNTAX
;
1511 case CVAR
: /* '$' */
1512 PARSESUB(); /* parse substitution */
1514 case CENDVAR
: /* '}' */
1516 ((state
[level
].category
== TSTATE_VAR_OLD
&&
1517 state
[level
].syntax
==
1518 state
[level
- 1].syntax
) ||
1519 (state
[level
].category
== TSTATE_VAR_NEW
&&
1520 state
[level
].syntax
== BASESYNTAX
))) {
1521 if (state
[level
].category
== TSTATE_VAR_NEW
)
1524 USTPUTC(CTLENDVAR
, out
);
1529 case CLP
: /* '(' in arithmetic */
1530 state
[level
].parenlevel
++;
1533 case CRP
: /* ')' in arithmetic */
1534 if (state
[level
].parenlevel
> 0) {
1536 --state
[level
].parenlevel
;
1538 if (pgetc_linecont() == ')') {
1540 state
[level
].category
== TSTATE_ARITH
) {
1542 USTPUTC(CTLENDARI
, out
);
1548 * (don't 2nd guess - no error)
1555 case CBQUOTE
: /* '`' */
1556 out
= parsebackq(out
, &bqlist
, 1,
1557 state
[level
].syntax
== DQSYNTAX
&&
1558 (eofmark
== NULL
|| newvarnest
> 0),
1559 state
[level
].syntax
== DQSYNTAX
|| state
[level
].syntax
== ARISYNTAX
);
1562 goto endword
; /* exit outer loop */
1567 goto endword
; /* exit outer loop */
1574 if (state
[level
].syntax
== ARISYNTAX
)
1575 synerror("Missing '))'");
1576 if (state
[level
].syntax
!= BASESYNTAX
&& eofmark
== NULL
)
1577 synerror("Unterminated quoted string");
1578 if (state
[level
].category
== TSTATE_VAR_OLD
||
1579 state
[level
].category
== TSTATE_VAR_NEW
) {
1580 startlinno
= plinno
;
1581 synerror("Missing '}'");
1583 if (state
!= state_static
)
1584 parser_temp_free_upto(state
);
1586 len
= out
- stackblock();
1588 if (eofmark
== NULL
) {
1589 if ((c
== '>' || c
== '<')
1592 && (*out
== '\0' || is_digit(*out
))) {
1594 return lasttoken
= TREDIR
;
1600 backquotelist
= bqlist
;
1601 grabstackblock(len
);
1603 return lasttoken
= TWORD
;
1604 /* end of readtoken routine */
1608 * Parse a substitution. At this point, we have read the dollar sign
1617 static const char types
[] = "}-+?=";
1622 c
= pgetc_linecont();
1623 if (c
== '(') { /* $(command) or $((arith)) */
1624 if (pgetc_linecont() == '(') {
1628 out
= parsebackq(out
, &bqlist
, 0,
1629 state
[level
].syntax
== DQSYNTAX
&&
1630 (eofmark
== NULL
|| newvarnest
> 0),
1631 state
[level
].syntax
== DQSYNTAX
||
1632 state
[level
].syntax
== ARISYNTAX
);
1634 } else if (c
== '{' || is_name(c
) || is_special(c
)) {
1635 USTPUTC(CTLVAR
, out
);
1636 typeloc
= out
- stackblock();
1637 USTPUTC(VSNORMAL
, out
);
1641 c
= pgetc_linecont();
1645 if (!is_eof(c
) && is_name(c
)) {
1649 c
= pgetc_linecont();
1651 } while (!is_eof(c
) && is_in_name(c
));
1653 strncmp(out
- length
, "LINENO", length
) == 0) {
1654 /* Replace the variable name with the
1655 * current line number. */
1657 CHECKSTRSPACE(11, out
);
1660 linno
-= funclinno
- 1;
1661 length
= snprintf(out
, 11, "%d", linno
);
1667 } else if (is_digit(c
)) {
1668 if (subtype
!= VSNORMAL
) {
1671 c
= pgetc_linecont();
1672 } while (is_digit(c
));
1675 c
= pgetc_linecont();
1677 } else if (is_special(c
)) {
1679 c
= pgetc_linecont();
1680 if (subtype
== 0 && c1
== '#') {
1682 if (strchr(types
, c
) == NULL
&& c
!= ':' &&
1683 c
!= '#' && c
!= '%')
1686 c
= pgetc_linecont();
1687 if (c1
!= '}' && c
== '}') {
1702 else if (c
== '\n' || c
== PEOF
)
1703 synerror("Unexpected end of line in substitution");
1704 else if (BASESYNTAX
[c
] != CCTL
)
1711 c
= pgetc_linecont();
1714 p
= strchr(types
, c
);
1716 if (c
== '\n' || c
== PEOF
)
1717 synerror("Unexpected end of line in substitution");
1720 if (BASESYNTAX
[c
] != CCTL
)
1724 subtype
= p
- types
+ VSNORMAL
;
1730 subtype
= c
== '#' ? VSTRIMLEFT
:
1732 c
= pgetc_linecont();
1740 } else if (subtype
!= VSERROR
) {
1741 if (subtype
== VSLENGTH
&& c
!= '}')
1746 if (state
[level
].syntax
== DQSYNTAX
||
1747 state
[level
].syntax
== ARISYNTAX
)
1749 *(stackblock() + typeloc
) = subtype
| flags
;
1750 if (subtype
!= VSNORMAL
) {
1751 if (level
+ 1 >= maxnest
) {
1753 if (state
== state_static
) {
1754 state
= parser_temp_alloc(
1755 maxnest
* sizeof(*state
));
1756 memcpy(state
, state_static
,
1757 MAXNEST_static
* sizeof(*state
));
1759 state
= parser_temp_realloc(state
,
1760 maxnest
* sizeof(*state
));
1763 state
[level
].parenlevel
= 0;
1764 if (subtype
== VSMINUS
|| subtype
== VSPLUS
||
1765 subtype
== VSQUESTION
|| subtype
== VSASSIGN
) {
1767 * For operators that were in the Bourne shell,
1768 * inherit the double-quote state.
1770 state
[level
].syntax
= state
[level
- 1].syntax
;
1771 state
[level
].category
= TSTATE_VAR_OLD
;
1774 * The other operators take a pattern,
1775 * so go to BASESYNTAX.
1776 * Also, ' and " are now special, even
1777 * in here documents.
1779 state
[level
].syntax
= BASESYNTAX
;
1780 state
[level
].category
= TSTATE_VAR_NEW
;
1784 } else if (c
== '\'' && state
[level
].syntax
== BASESYNTAX
) {
1785 /* $'cstylequotes' */
1786 USTPUTC(CTLQUOTEMARK
, out
);
1787 state
[level
].syntax
= SQSYNTAX
;
1793 goto parsesub_return
;
1798 * Parse an arithmetic expansion (indicate start of one and set state)
1802 if (level
+ 1 >= maxnest
) {
1804 if (state
== state_static
) {
1805 state
= parser_temp_alloc(
1806 maxnest
* sizeof(*state
));
1807 memcpy(state
, state_static
,
1808 MAXNEST_static
* sizeof(*state
));
1810 state
= parser_temp_realloc(state
,
1811 maxnest
* sizeof(*state
));
1814 state
[level
].syntax
= ARISYNTAX
;
1815 state
[level
].parenlevel
= 0;
1816 state
[level
].category
= TSTATE_ARITH
;
1817 USTPUTC(CTLARI
, out
);
1818 if (state
[level
- 1].syntax
== DQSYNTAX
)
1822 goto parsearith_return
;
1825 } /* end of readtoken */
1829 * Returns true if the text contains nothing to expand (no dollar signs
1834 noexpand(char *text
)
1840 while ((c
= *p
++) != '\0') {
1841 if ( c
== CTLQUOTEMARK
)
1845 else if (BASESYNTAX
[(int)c
] == CCTL
)
1853 * Return true if the argument is a legal variable name (a letter or
1854 * underscore followed by zero or more letters, underscores, and digits).
1858 goodname(const char *name
)
1866 if (! is_in_name(*p
))
1874 isassignment(const char *p
)
1882 else if (!is_in_name(*p
))
1890 consumetoken(int token
)
1892 if (readtoken() != token
)
1898 * Called when an unexpected token is read during the parse. The argument
1899 * is the token that is expected, or -1 if more than one type of token can
1900 * occur at this point.
1904 synexpect(int token
)
1909 fmtstr(msg
, 64, "%s unexpected (expecting %s)",
1910 tokname
[lasttoken
], tokname
[token
]);
1912 fmtstr(msg
, 64, "%s unexpected", tokname
[lasttoken
]);
1919 synerror(const char *msg
)
1922 outfmt(out2
, "%s: %d: ", commandname
, startlinno
);
1924 outfmt(out2
, "%s: ", arg0
);
1925 outfmt(out2
, "Syntax error: %s\n", msg
);
1926 error((char *)NULL
);
1930 setprompt(int which
)
1932 whichprompt
= which
;
1940 out2str(getprompt(NULL
));
1946 pgetc_linecont(void)
1950 while ((c
= pgetc_macro()) == '\\') {
1960 /* Allow the backslash to be pushed back. */
1961 pushstring("\\", 1, NULL
);
1969 * called by editline -- any expansions to the prompt
1970 * should be added here.
1973 getprompt(void *unused __unused
)
1975 static char ps
[PROMPTLEN
];
1979 static char internal_error
[] = "??";
1982 * Select prompt format.
1984 switch (whichprompt
) {
1995 return internal_error
;
1999 * Format prompt string.
2001 for (i
= 0; (i
< PROMPTLEN
- 1) && (*fmt
!= '\0'); i
++, fmt
++)
2008 * \h specifies just the local hostname,
2009 * \H specifies fully-qualified hostname.
2014 gethostname(&ps
[i
], PROMPTLEN
- i
- 1);
2015 ps
[PROMPTLEN
- 1] = '\0';
2016 /* Skip to end of hostname. */
2017 trim
= (*fmt
== 'h') ? '.' : '\0';
2018 while ((ps
[i
] != '\0') && (ps
[i
] != trim
))
2024 * Working directory.
2026 * \W specifies just the final component,
2027 * \w specifies the entire path.
2031 pwd
= lookupvar("PWD");
2032 if (pwd
== NULL
|| *pwd
== '\0')
2035 *pwd
== '/' && pwd
[1] != '\0')
2036 strlcpy(&ps
[i
], strrchr(pwd
, '/') + 1,
2039 strlcpy(&ps
[i
], pwd
, PROMPTLEN
- i
);
2040 /* Skip to end of path. */
2041 while (ps
[i
+ 1] != '\0')
2048 * '$' for normal users, '#' for root.
2051 ps
[i
] = (geteuid() != 0) ? '$' : '#';
2062 * Emit unrecognized formats verbatim.
2066 if (i
< PROMPTLEN
- 2)
2078 expandstr(const char *ps
)
2081 struct jmploc jmploc
;
2082 struct jmploc
*const savehandler
= handler
;
2083 const int saveprompt
= doprompt
;
2084 struct parsefile
*const savetopfile
= getcurrentfile();
2085 struct parser_temp
*const saveparser_temp
= parser_temp
;
2086 const char *result
= NULL
;
2088 if (!setjmp(jmploc
.loc
)) {
2091 setinputstring(ps
, 1);
2093 readtoken1(pgetc(), DQSYNTAX
, NOEOFMARK
, 0);
2094 if (backquotelist
!= NULL
)
2095 error("Command substitution not allowed here");
2099 n
.narg
.text
= wordtext
;
2100 n
.narg
.backquote
= backquotelist
;
2102 expandarg(&n
, NULL
, 0);
2103 result
= stackblock();
2106 handler
= savehandler
;
2107 doprompt
= saveprompt
;
2108 popfilesupto(savetopfile
);
2109 if (parser_temp
!= saveparser_temp
) {
2110 parser_temp_free_all();
2111 parser_temp
= saveparser_temp
;
2113 if (result
!= NULL
) {
2115 } else if (exception
== EXINT
)