1 /* $OpenBSD: lex.c,v 1.45 2011/03/09 09:30:39 okan Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
5 * Thorsten Glaser <tg@mirbsd.org>
7 * Provided that these terms and disclaimer and all copyright notices
8 * are retained or reproduced in an accompanying document, permission
9 * is granted to deal in this work without restriction, including un-
10 * limited rights to use, publicly perform, distribute, sell, modify,
11 * merge, give away, or sublicence.
13 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
14 * the utmost extent permitted by applicable law, neither express nor
15 * implied; without malicious intent or gross negligence. In no event
16 * may a licensor, author or contributor be held liable for indirect,
17 * direct, other damage, loss, or other issues arising in any way out
18 * of dealing in the work, even if advised of the possibility of such
19 * damage or existence of a defect, except proven that it results out
20 * of said person's immediate fault when using the work as intended.
25 __RCSID("$MirOS: src/bin/mksh/lex.c,v 1.156 2011/09/07 15:24:16 tg Exp $");
28 * states while lexing word
30 #define SBASE 0 /* outside any lexical constructs */
31 #define SWORD 1 /* implicit quoting for substitute() */
32 #define SLETPAREN 2 /* inside (( )), implicit quoting */
33 #define SSQUOTE 3 /* inside '' */
34 #define SDQUOTE 4 /* inside "" */
35 #define SEQUOTE 5 /* inside $'' */
36 #define SBRACE 6 /* inside ${} */
37 #define SQBRACE 7 /* inside "${}" */
38 #define SBQUOTE 8 /* inside `` */
39 #define SASPAREN 9 /* inside $(( )) */
40 #define SHEREDELIM 10 /* parsing <<,<<- delimiter */
41 #define SHEREDQUOTE 11 /* parsing " in <<,<<- delimiter */
42 #define SPATTERN 12 /* parsing *(...|...) pattern (*+?@!) */
43 #define SADELIM 13 /* like SBASE, looking for delimiter */
44 #define SHERESTRING 14 /* parsing <<< string */
45 #define STBRACEKORN 15 /* parsing ${...[#%]...} !FSH */
46 #define STBRACEBOURNE 16 /* parsing ${...[#%]...} FSH */
47 #define SINVALID 255 /* invalid state */
49 struct sretrace_info {
50 struct sretrace_info *next;
56 * Structure to keep track of the lexing state and the various pieces of info
57 * needed for each particular state.
59 typedef struct lex_state {
61 /* point to the next state block */
62 struct lex_state *base;
63 /* marks start of state output in output string */
65 /* SBQUOTE: true if in double quotes: "`...`" */
66 /* SEQUOTE: got NUL, ignore rest of string */
68 /* SADELIM information */
70 /* character to search for */
71 unsigned char delimiter;
72 /* max. number of delimiters */
76 /* count open parentheses */
78 /* type of this state */
81 #define ls_base u.base
82 #define ls_start u.start
83 #define ls_bool u.abool
84 #define ls_adelim u.adelim
91 static void readhere(struct ioword *);
92 static void ungetsc(int);
93 static void ungetsc_(int);
94 static int getsc_uu(void);
95 static void getsc_line(Source *);
96 static int getsc_bn(void);
97 static int s_get(void);
98 static void s_put(int);
99 static char *get_brace_var(XString *, char *);
100 static bool arraysub(char **);
101 static void gethere(bool);
102 static Lex_state *push_state_(State_info *, Lex_state *);
103 static Lex_state *pop_state_(State_info *, Lex_state *);
105 static int dopprompt(const char *, int, bool);
106 void yyskiputf8bom(void);
108 static int backslash_skip;
109 static int ignore_backslash_newline;
110 static struct sretrace_info *retrace_info;
111 short subshell_nesting_level = 0;
113 /* optimised getsc_bn() */
114 #define o_getsc() (*source->str != '\0' && *source->str != '\\' && \
115 !backslash_skip ? *source->str++ : getsc_bn())
116 /* optimised getsc_uu() */
117 #define o_getsc_u() ((*source->str != '\0') ? *source->str++ : getsc_uu())
120 #define o_getsc_r(carg) { \
122 struct sretrace_info *rp = retrace_info; \
125 Xcheck(rp->xs, rp->xp); \
134 static int getsc(void);
139 o_getsc_r(o_getsc());
142 static int getsc_r(int);
150 #define getsc() getsc_r(o_getsc())
153 #define STATE_BSIZE 8
155 #define PUSH_STATE(s) do { \
156 if (++statep == state_info.end) \
157 statep = push_state_(&state_info, statep); \
158 state = statep->type = (s); \
159 } while (/* CONSTCOND */ 0)
161 #define POP_STATE() do { \
162 if (--statep == state_info.base) \
163 statep = pop_state_(&state_info, statep); \
164 state = statep->type; \
165 } while (/* CONSTCOND */ 0)
167 #define PUSH_SRETRACE() do { \
168 struct sretrace_info *ri; \
170 statep->ls_start = Xsavepos(ws, wp); \
171 ri = alloc(sizeof(struct sretrace_info), ATEMP); \
172 Xinit(ri->xs, ri->xp, 64, ATEMP); \
173 ri->next = retrace_info; \
175 } while (/* CONSTCOND */ 0)
177 #define POP_SRETRACE() do { \
178 wp = Xrestpos(ws, wp, statep->ls_start); \
179 *retrace_info->xp = '\0'; \
180 sp = Xstring(retrace_info->xs, retrace_info->xp); \
181 dp = (void *)retrace_info; \
182 retrace_info = retrace_info->next; \
184 } while (/* CONSTCOND */ 0)
189 * tokens are not regular expressions, they are LL(1).
190 * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
191 * hence the state stack. Note "$(...)" are now parsed recursively.
197 Lex_state states[STATE_BSIZE], *statep, *s2, *base;
198 State_info state_info;
201 XString ws; /* expandable output word */
202 char *wp; /* output word pointer */
206 states[0].type = SINVALID;
207 states[0].ls_base = NULL;
209 state_info.base = states;
210 state_info.end = &state_info.base[STATE_BSIZE];
212 Xinit(ws, wp, 64, ATEMP);
215 ignore_backslash_newline = 0;
219 else if (cf & LETEXPR) {
220 /* enclose arguments in (double) quotes */
226 state = (cf & HEREDELIM) ? SHEREDELIM : SBASE;
227 while ((c = getsc()) == ' ' || c == '\t')
230 ignore_backslash_newline++;
231 while ((c = getsc()) != '\0' && c != '\n')
233 ignore_backslash_newline--;
237 if (source->flags & SF_ALIAS) {
238 /* trailing ' ' in alias definition */
239 source->flags &= ~SF_ALIAS;
243 /* Initial state: one of SWORD SLETPAREN SHEREDELIM SBASE */
244 statep->type = state;
246 /* check for here string */
247 if (state == SHEREDELIM) {
251 while ((c = getsc()) == ' ' || c == '\t')
260 /* collect non-special or quoted characters to form word */
261 while (!((c = getsc()) == 0 ||
262 ((state == SBASE || state == SHEREDELIM || state == SHERESTRING) &&
263 ctype(c, C_LEX1)))) {
272 else if (statep->nparen == 0 &&
273 (c == /*{*/ '}' || c == statep->ls_adelim.delimiter)) {
276 if (c == /*{*/ '}' || --statep->ls_adelim.num == 0)
284 if (c == '[' && (cf & (VARASN|ARRAYVAR))) {
287 if (is_wdvarname(Xstring(ws, wp), false)) {
290 if (arraysub(&tmp)) {
293 for (p = tmp; *p; ) {
316 Sbase1: /* includes *(...|...) pattern (*+?@!) */
317 if (c == '*' || c == '@' || c == '+' || c == '?' ||
320 if (c2 == '(' /*)*/ ) {
323 PUSH_STATE(SPATTERN);
329 Sbase2: /* doesn't include *(...|...) pattern (*+?@!) */
334 /* trailing \ is lost */
342 ignore_backslash_newline++;
374 /* trailing \ is lost */
386 if (c == '(') /*)*/ {
388 if (c == '(') /*)*/ {
390 PUSH_STATE(SASPAREN);
393 *retrace_info->xp++ = '(';
404 } else if (c == '{') /*}*/ {
407 wp = get_brace_var(&ws, wp);
409 /* allow :# and :% (ksh88 compat) */
421 statep->ls_adelim.delimiter = ':';
422 statep->ls_adelim.num = 1;
425 } else if (ksh_isdigit(c) ||
426 c == '('/*)*/ || c == ' ' ||
429 /* substring subst. */
437 statep->ls_adelim.delimiter = ':';
438 statep->ls_adelim.num = 2;
442 } else if (c == '/') {
445 if ((c = getsc()) == '/') {
452 statep->ls_adelim.delimiter = '/';
453 statep->ls_adelim.num = 1;
458 * If this is a trim operation,
459 * treat (,|,) specially in STBRACE.
461 if (ctype(c, C_SUBOP2)) {
464 PUSH_STATE(STBRACEBOURNE);
466 PUSH_STATE(STBRACEKORN);
469 if (state == SDQUOTE)
474 } else if (ksh_isalphx(c)) {
481 } while (ksh_isalnux(c));
486 } else if (ctype(c, C_VAR1 | C_DIGIT)) {
494 } else if (c == '\'' && (state == SBASE)) {
495 /* XXX which other states are valid? */
497 ignore_backslash_newline++;
499 statep->ls_bool = false;
501 } else if (c == '"' && (state == SBASE)) {
502 /* XXX which other states are valid? */
516 * Need to know if we are inside double quotes
517 * since sh/AT&T-ksh translate the \" to " in
519 * This is not done in POSIX mode (section
520 * 3.2.3, Double Quotes: "The backquote shall
521 * retain its special meaning introducing the
522 * other form of command substitution (see
523 * 3.6.3). The portion of the quoted string
524 * from the initial backquote and the
525 * characters up to the next backquote that
526 * is not preceded by a backslash (having
527 * escape characters removed) defines that
528 * command whose output replaces `...` when
529 * the word is expanded."
530 * Section 3.6.3, Command Substitution:
531 * "Within the backquoted style of command
532 * substitution, backslash shall retain its
533 * literal meaning, except when followed by
536 statep->ls_bool = false;
538 base = state_info.base;
539 while (/* CONSTCOND */ 1) {
540 for (; s2 != base; s2--) {
541 if (s2->type == SDQUOTE) {
542 statep->ls_bool = true;
548 if (!(s2 = s2->ls_base))
550 base = s2-- - STATE_BSIZE;
571 ignore_backslash_newline--;
572 } else if (c == '\\') {
573 if ((c2 = unbksl(true, s_get, s_put)) == -1)
576 statep->ls_bool = true;
577 if (!statep->ls_bool) {
580 if ((unsigned int)c2 < 0x100) {
584 cz = utf_wctomb(ts, c2 - 0x100);
586 for (cz = 0; ts[cz]; ++cz) {
592 } else if (!statep->ls_bool) {
602 ignore_backslash_newline--;
623 if (statep->nparen == 1) {
628 if ((c2 = getsc()) == /*(*/ ')') {
631 memcpy(wp, sp + 1, cz);
641 * mismatched parenthesis -
642 * assume we were really
643 * parsing a $(...) expression
656 /* reuse existing state machine */
662 * perform POSIX "quote removal" if the back-
663 * slash is "special", i.e. same cases as the
664 * {case '\\':} in Subst: plus closing brace;
665 * in mksh code "quote removal" on '\c' means
666 * write QCHAR+c, otherwise CHAR+\+CHAR+c are
667 * emitted (in heredocquote:)
669 if ((c = getsc()) == '"' || c == '\\' ||
670 c == '$' || c == '`' || c == /*{*/'}')
688 else if (c != /*{*/ '}')
695 /* Same as SBASE, except (,|,) treated specially */
703 PUSH_STATE(SPATTERN);
704 } else /* FALLTHROUGH */
706 if (c == /*{*/ '}') {
718 } else if (c == '\\') {
719 switch (c = getsc()) {
721 /* trailing \ is lost */
728 if (statep->ls_bool) {
746 /* LETEXPR: (( ... )) */
748 if (c == /*(*/ ')') {
749 if (statep->nparen > 0)
751 else if ((c2 = getsc()) == /*(*/ ')') {
760 * mismatched parenthesis -
761 * assume we were really
762 * parsing a (...) expression
765 sp = Xstring(ws, wp);
766 dp = wdstrip(sp, WDS_KEEPQ);
767 s = pushs(SREREAD, source->areap);
768 s->start = s->str = s->u.freeme = dp;
775 * parentheses inside quotes and
776 * backslashes are lost, but AT&T ksh
777 * doesn't count them either
787 /* trailing \ is lost */
791 } else if (c == '$') {
792 if ((c2 = getsc()) == '\'') {
794 statep->ls_bool = false;
795 goto sherestring_quoted;
796 } else if (c2 == '"')
797 goto sherestring_dquoted;
799 goto sherestring_regular;
800 } else if (c == '\'') {
804 ignore_backslash_newline++;
805 } else if (c == '"') {
807 state = statep->type = SHEREDQUOTE;
809 /* just don't IFS split; no quoting mode */
817 /* <<,<<- delimiter */
820 * XXX chuck this state (and the next) - use
821 * the existing states ($ and \`...` should be
822 * stripped of their specialness after the
826 * here delimiters need a special case since
827 * $ and `...` are not to be treated specially
832 /* trailing \ is lost */
836 } else if (c == '$') {
837 if ((c2 = getsc()) == '\'') {
839 statep->ls_bool = false;
840 goto sheredelim_quoted;
841 } else if (c2 == '"')
842 goto sheredelim_dquoted;
844 goto sheredelim_regular;
845 } else if (c == '\'') {
849 ignore_backslash_newline++;
850 } else if (c == '"') {
852 state = statep->type = SHEREDQUOTE;
861 /* " in <<,<<- delimiter */
865 state = statep->type =
866 /* dp[1] == '<' means here string */
867 Xstring(ws, wp)[1] == '<' ?
868 SHERESTRING : SHEREDELIM;
871 switch (c = getsc()) {
873 /* trailing \ is lost */
890 /* in *(...|...) pattern (*+?@!) */
892 if (c == /*(*/ ')') {
895 } else if (c == '|') {
897 } else if (c == '(') {
901 PUSH_STATE(SPATTERN);
909 if (statep != &states[1])
910 /* XXX figure out what is missing */
911 yyerror("no closing quote\n");
913 /* This done to avoid tests for SHEREDELIM wherever SBASE tested */
914 if (state == SHEREDELIM || state == SHERESTRING)
917 dp = Xstring(ws, wp);
918 if ((c == '<' || c == '>' || c == '&') && state == SBASE) {
919 struct ioword *iop = alloc(sizeof(struct ioword), ATEMP);
921 if (Xlength(ws, wp) == 0)
922 iop->unit = c == '<' ? 0 : 1;
923 else for (iop->unit = 0, c2 = 0; c2 < Xlength(ws, wp); c2 += 2) {
926 if (!ksh_isdigit(dp[c2 + 1]))
928 iop->unit = (iop->unit * 10) + dp[c2 + 1] - '0';
931 if (iop->unit >= FDBASE)
935 if ((c2 = getsc()) != '>') {
945 /* <<, >>, <> are ok, >< is not */
946 if (c == c2 || (c == '<' && c2 == '>')) {
947 iop->flag |= c == c2 ?
948 (c == '>' ? IOCAT : IOHERE) : IORDWR;
949 if (iop->flag == IOHERE) {
950 if ((c2 = getsc()) == '-') {
953 } else if (c2 == '<')
954 iop->flag |= IOHERESTR;
957 iop->flag |= IONDELIM;
959 } else if (c2 == '&')
960 iop->flag |= IODUP | (c == '<' ? IORDUP : 0);
962 iop->flag |= c == '>' ? IOWRITE : IOREAD;
963 if (c == '>' && c2 == '|')
980 if (wp == dp && state == SBASE) {
983 /* no word, process LEX1 character */
984 if ((c == '|') || (c == '&') || (c == ';') || (c == '('/*)*/)) {
985 if ((c2 = getsc()) == c)
986 c = (c == ';') ? BREAK :
988 (c == '&') ? LOGAND :
989 /* c == '(' ) */ MDPAREN;
990 else if (c == '|' && c2 == '&')
992 else if (c == ';' && c2 == '|')
994 else if (c == ';' && c2 == '&')
1000 if ((c2 = getsc()) == '&')
1006 } else if (c == '\n') {
1010 } else if (c == '\0')
1011 /* need here strings at EOF */
1016 /* terminate word */
1018 yylval.cp = Xclose(ws, wp);
1019 if (state == SWORD || state == SLETPAREN
1023 /* unget terminator */
1027 * note: the alias-vs-function code below depends on several
1028 * interna: starting from here, source->str is not modified;
1029 * the way getsc() and ungetsc() operate; etc.
1032 /* copy word to unprefixed string ident */
1035 if ((cf & HEREDELIM) && (sp[1] == '<'))
1036 while (dp < ident+IDENT) {
1037 if ((c = *sp++) == CHAR)
1039 else if ((c != OQUOTE) && (c != CQUOTE))
1043 while (dp < ident+IDENT && (c = *sp++) == CHAR)
1045 /* Make sure the ident array stays '\0' padded */
1046 memset(dp, 0, (ident+IDENT) - dp + 1);
1048 /* word is not unquoted */
1051 if (*ident != '\0' && (cf & (KEYWORD | ALIAS))) {
1053 uint32_t h = hash(ident);
1055 if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
1056 (!(cf & ESACONLY) || p->val.i == ESAC ||
1057 p->val.i == /*{*/ '}')) {
1058 afree(yylval.cp, ATEMP);
1061 if ((cf & ALIAS) && (p = ktsearch(&aliases, ident, h)) &&
1062 (p->flag & ISSET)) {
1064 * this still points to the same character as the
1065 * ungetsc'd terminator from above
1067 const char *cp = source->str;
1069 /* prefer POSIX but not Korn functions over aliases */
1070 while (*cp == ' ' || *cp == '\t')
1072 * this is like getsc() without skipping
1073 * over Source boundaries (including not
1074 * parsing ungetsc'd characters that got
1075 * pushed into an SREREAD) which is what
1076 * we want here anyway: find out whether
1077 * the alias name is followed by a POSIX
1078 * function definition (only the opening
1079 * parenthesis is checked though)
1082 /* prefer functions over aliases */
1083 if (cp[0] != '(' || cp[1] != ')') {
1086 while (s && (s->flags & SF_HASALIAS))
1091 /* push alias expansion */
1092 s = pushs(SALIAS, source->areap);
1093 s->start = s->str = p->val.s;
1095 s->flags |= SF_HASALIAS;
1097 if (source->type == SEOF) {
1098 /* prevent infinite recursion at EOS */
1100 source->flags |= SF_HASALIAS;
1103 afree(yylval.cp, ATEMP);
1117 for (p = heres; p < herep; p++)
1118 if (iseof && !((*p)->flag & IOHERESTR))
1119 /* only here strings at EOF */
1127 * read "<<word" text into temp file
1131 readhere(struct ioword *iop)
1134 const char *eof, *eofp;
1139 if (iop->flag & IOHERESTR) {
1140 /* process the here string */
1141 iop->heredoc = xp = evalstr(iop->delim, DOBLANK);
1142 xpos = strlen(xp) - 1;
1143 memmove(xp, xp + 1, xpos);
1148 eof = iop->flag & IONDELIM ? "<<" : evalstr(iop->delim, 0);
1150 if (!(iop->flag & IOEVAL))
1151 ignore_backslash_newline++;
1153 Xinit(xs, xp, 256, ATEMP);
1156 /* beginning of line */
1158 xpos = Xsavepos(xs, xp);
1159 if (iop->flag & IOSKIP) {
1160 /* skip over leading tabs */
1161 while ((c = getsc()) == '\t')
1163 goto heredoc_parse_char;
1168 /* compare with here document marker */
1170 /* end of here document marker, what to do? */
1173 if (!subshell_nesting_level)
1175 * not allowed outside $(...) or (...)
1179 /* allow $(...) or (...) to close here */
1184 * Allow EOF here to commands without trailing
1185 * newlines (mksh -c '...') will work as well.
1188 /* Newline terminates here document marker */
1189 goto heredoc_found_terminator;
1191 } else if (c == *eofp++)
1192 /* store; then read and compare next character */
1193 goto heredoc_store_and_loop;
1194 /* nope, mismatch; read until end of line */
1197 /* oops, reached EOF */
1198 yyerror("%s '%s' unclosed\n", "here document", eof);
1199 /* store character */
1202 /* read next character */
1205 /* we read a newline as last character */
1206 heredoc_store_and_loop:
1207 /* store character */
1211 goto heredoc_read_line;
1212 goto heredoc_read_char;
1214 heredoc_found_terminator:
1215 /* jump back to saved beginning of line */
1216 xp = Xrestpos(xs, xp, xpos);
1217 /* terminate, close and store */
1219 iop->heredoc = Xclose(xs, xp);
1221 if (!(iop->flag & IOEVAL))
1222 ignore_backslash_newline--;
1226 yyerror(const char *fmt, ...)
1230 /* pop aliases and re-reads */
1231 while (source->type == SALIAS || source->type == SREREAD)
1232 source = source->next;
1233 /* zap pending input */
1238 shf_vfprintf(shl_out, fmt, va);
1244 * input for yylex with alias expansion
1248 pushs(int type, Area *areap)
1252 s = alloc(sizeof(Source), areap);
1253 memset(s, 0, sizeof(Source));
1257 if (type == SFILE || type == SSTDIN)
1258 XinitN(s->xs, 256, s->areap);
1268 while ((c = *s->str++) == 0) {
1269 /* return 0 for EOF by default */
1288 s->start = s->str = *s->u.strv++;
1293 if (*s->u.strv == NULL) {
1294 s->start = s->str = "\n";
1297 s->start = s->str = " ";
1303 if (s->flags & SF_ALIASEND) {
1304 /* pass on an unused SF_ALIAS flag */
1306 source->flags |= s->flags & SF_ALIAS;
1308 } else if (*s->u.tblp->val.s &&
1309 (c = strnul(s->u.tblp->val.s)[-1], ksh_isspace(c))) {
1310 /* pop source stack */
1311 source = s = s->next;
1313 * Note that this alias ended with a
1314 * space, enabling alias expansion on
1315 * the following word.
1317 s->flags |= SF_ALIAS;
1320 * At this point, we need to keep the current
1321 * alias in the source list so recursive
1322 * aliases can be detected and we also need to
1323 * return the next character. Do this by
1324 * temporarily popping the alias to get the
1325 * next character and then put it back in the
1326 * source list with the SF_ALIASEND flag set.
1328 /* pop source stack */
1330 source->flags |= s->flags & SF_ALIAS;
1333 s->flags |= SF_ALIASEND;
1334 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1335 s->start = s->str = s->ugbuf;
1340 /* avoid reading EOF twice */
1348 if (s->start != s->ugbuf)
1350 afree(s->u.freeme, ATEMP);
1351 source = s = s->next;
1354 if (s->str == NULL) {
1356 s->start = s->str = null;
1359 if (s->flags & SF_ECHO) {
1360 shf_puts(s->str, shl_out);
1368 getsc_line(Source *s)
1370 char *xp = Xstring(s->xs, xp), *cp;
1371 bool interactive = Flag(FTALKING) && s->type == SSTDIN;
1372 int have_tty = interactive && (s->flags & SF_TTY);
1374 /* Done here to ensure nothing odd happens when a timeout occurs */
1375 XcheckN(s->xs, xp, LINE);
1377 s->start = s->str = xp;
1379 if (have_tty && ksh_tmout) {
1380 ksh_tmout_state = TMOUT_READING;
1389 Flag(FEMACS) || Flag(FGMACS))) {
1392 nread = x_read(xp, LINE);
1404 while (/* CONSTCOND */ 1) {
1405 char *p = shf_getse(xp, Xnleft(s->xs, xp), s->u.shf);
1407 if (!p && shf_error(s->u.shf) &&
1408 shf_errno(s->u.shf) == EINTR) {
1409 shf_clearerr(s->u.shf);
1414 if (!p || (xp = p, xp[-1] == '\n'))
1416 /* double buffer size */
1417 /* move past NUL so doubling works... */
1419 XcheckN(s->xs, xp, Xlength(s->xs, xp));
1420 /* ...and move back again */
1424 * flush any unwanted input so other programs/builtins
1425 * can read it. Not very optimal, but less error prone
1426 * than flushing else where, dealing with redirections,
1428 * TODO: reduce size of shf buffer (~128?) if SSTDIN
1430 if (s->type == SSTDIN)
1431 shf_flush(s->u.shf);
1434 * XXX: temporary kludge to restore source after a
1435 * trap may have been executed.
1438 if (have_tty && ksh_tmout) {
1439 ksh_tmout_state = TMOUT_EXECUTING;
1442 cp = Xstring(s->xs, xp);
1444 if (interactive && *cp == '!' && cur_prompt == PS1) {
1447 linelen = Xlength(s->xs, xp);
1448 XcheckN(s->xs, xp, Zfc_e_dash + /* NUL */ 1);
1449 /* reload after potential realloc */
1450 cp = Xstring(s->xs, xp);
1451 /* change initial '!' into space */
1453 /* NUL terminate the current string */
1455 /* move the actual string forward */
1456 memmove(cp + Zfc_e_dash, cp, linelen + /* NUL */ 1);
1458 /* prepend it with "fc -e -" */
1459 memcpy(cp, Tfc_e_dash, Zfc_e_dash);
1462 s->start = s->str = cp;
1463 strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
1464 /* Note: if input is all nulls, this is not eof */
1465 if (Xlength(s->xs, xp) == 0) {
1467 if (s->type == SFILE)
1468 shf_fdclose(s->u.shf);
1470 } else if (interactive && *s->str &&
1471 (cur_prompt != PS1 || !ctype(*s->str, C_IFS | C_IFSWS))) {
1472 histsave(&s->line, s->str, true, true);
1473 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
1474 } else if (interactive && cur_prompt == PS1) {
1475 cp = Xstring(s->xs, xp);
1476 while (*cp && ctype(*cp, C_IFSWS))
1483 set_prompt(PS2, NULL);
1487 set_prompt(int to, Source *s)
1495 * Substitute ! and !! here, before substitutions are done
1496 * so ! in expanded variables are not expanded.
1497 * NOTE: this is not what AT&T ksh does (it does it after
1498 * substitutions, POSIX doesn't say which is to be done.
1502 char * volatile ps1;
1505 ps1 = str_val(global("PS1"));
1506 shf = shf_sopen(NULL, strlen(ps1) * 2,
1507 SHF_WR | SHF_DYNAMIC, NULL);
1509 if (*ps1 != '!' || *++ps1 == '!')
1510 shf_putchar(*ps1++, shf);
1512 shf_fprintf(shf, "%d",
1513 s ? s->line + 1 : 0);
1514 ps1 = shf_sclose(shf);
1515 saved_atemp = ATEMP;
1517 if (sigsetjmp(e->jbuf, 0)) {
1518 prompt = safe_prompt;
1520 * Don't print an error - assume it has already
1521 * been printed. Reason is we may have forked
1522 * to run a command and the child may be
1523 * unwinding its stack through this code as it
1527 char *cp = substitute(ps1, 0);
1528 strdupx(prompt, cp, saved_atemp);
1533 /* command continuation */
1535 prompt = str_val(global("PS2"));
1541 dopprompt(const char *cp, int ntruncate, bool doprint)
1543 int columns = 0, lines = 0, indelimit = 0;
1547 * Undocumented AT&T ksh feature:
1548 * If the second char in the prompt string is \r then the first
1549 * char is taken to be a non-printing delimiter and any chars
1550 * between two instances of the delimiter are not considered to
1551 * be part of the prompt length
1553 if (*cp && cp[1] == '\r') {
1558 if (indelimit && *cp != delimiter)
1560 else if (*cp == '\n' || *cp == '\r') {
1561 lines += columns / x_cols + ((*cp == '\n') ? 1 : 0);
1563 } else if (*cp == '\t') {
1564 columns = (columns | 7) + 1;
1565 } else if (*cp == '\b') {
1568 } else if (*cp == delimiter)
1569 indelimit = !indelimit;
1570 else if (UTFMODE && ((unsigned char)*cp > 0x7F)) {
1572 columns += utf_widthadj(cp, &cp2);
1573 if (doprint && (indelimit ||
1574 (ntruncate < (x_cols * lines + columns))))
1575 shf_write(cp, cp2 - cp, shl_out);
1576 cp = cp2 - /* loop increment */ 1;
1580 if (doprint && (*cp != delimiter) &&
1581 (indelimit || (ntruncate < (x_cols * lines + columns))))
1582 shf_putc(*cp, shl_out);
1586 return (x_cols * lines + columns);
1591 pprompt(const char *cp, int ntruncate)
1593 dopprompt(cp, ntruncate, true);
1597 promptlen(const char *cp)
1599 return (dopprompt(cp, 0, false));
1603 * Read the variable part of a ${...} expression (i.e. up to but not
1604 * including the :[-+?=#%] or close-brace).
1607 get_brace_var(XString *wsp, char *wp)
1611 PS_INITIAL, PS_SAW_HASH, PS_IDENT,
1613 } state = PS_INITIAL;
1615 while (/* CONSTCOND */ 1) {
1617 /* State machine to figure out where the variable part ends. */
1620 if (c == '#' || c == '!' || c == '%') {
1621 state = PS_SAW_HASH;
1628 else if (ksh_isdigit(c))
1630 else if (c == '#') {
1631 if (state == PS_SAW_HASH) {
1642 } else if (ctype(c, C_VAR1))
1648 if (!ksh_isalnux(c)) {
1652 if (!arraysub(&tmp))
1653 yyerror("missing ]\n");
1655 for (p = tmp; *p; ) {
1667 if (!ksh_isdigit(c))
1677 /* end of variable part */
1684 * Save an array subscript - returns true if matching bracket found, false
1685 * if eof or newline was found.
1686 * (Returned string double null terminated)
1689 arraysub(char **strp)
1693 /* we are just past the initial [ */
1696 Xinit(ws, wp, 32, ATEMP);
1706 } while (depth > 0 && c && c != '\n');
1709 *strp = Xclose(ws, wp);
1711 return (tobool(depth == 0));
1714 /* Unget a char: handles case when we are already at the start of the buffer */
1718 struct sretrace_info *rp = retrace_info;
1722 /* Don't unget EOF... */
1723 if (source->str == null && c == '\0')
1726 if (Xlength(rp->xs, rp->xp))
1735 if (source->str > source->start)
1740 s = pushs(SREREAD, source->areap);
1741 s->ugbuf[0] = c; s->ugbuf[1] = '\0';
1742 s->start = s->str = s->ugbuf;
1749 /* Called to get a char that isn't a \newline sequence. */
1755 if (ignore_backslash_newline)
1756 return (o_getsc_u());
1758 if (backslash_skip == 1) {
1760 return (o_getsc_u());
1765 while (/* CONSTCOND */ 1) {
1768 if ((c2 = o_getsc_u()) == '\n')
1769 /* ignore the \newline; get the next char... */
1783 if ((unsigned char)(c = o_getsc_u()) != 0xEF) {
1787 if ((unsigned char)(c = o_getsc_u()) != 0xBB) {
1792 if ((unsigned char)(c = o_getsc_u()) != 0xBF) {
1802 push_state_(State_info *si, Lex_state *old_end)
1804 Lex_state *news = alloc2(STATE_BSIZE, sizeof(Lex_state), ATEMP);
1806 news[0].ls_base = old_end;
1807 si->base = &news[0];
1808 si->end = &news[STATE_BSIZE];
1813 pop_state_(State_info *si, Lex_state *old_end)
1815 Lex_state *old_base = si->base;
1817 si->base = old_end->ls_base - STATE_BSIZE;
1818 si->end = old_end->ls_base;
1820 afree(old_base, ATEMP);
1822 return (si->base + STATE_BSIZE - 1);