OSDN Git Service

c50c2ab9c71221e5ea897d0f7954049905e4b9a9
[android-x86/external-mksh.git] / src / syn.c
1 /*      $OpenBSD: syn.c,v 1.30 2015/09/01 13:12:31 tedu Exp $   */
2
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009,
5  *               2011, 2012, 2013, 2014, 2015, 2016, 2017
6  *      mirabilos <m@mirbsd.org>
7  *
8  * Provided that these terms and disclaimer and all copyright notices
9  * are retained or reproduced in an accompanying document, permission
10  * is granted to deal in this work without restriction, including un-
11  * limited rights to use, publicly perform, distribute, sell, modify,
12  * merge, give away, or sublicence.
13  *
14  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15  * the utmost extent permitted by applicable law, neither express nor
16  * implied; without malicious intent or gross negligence. In no event
17  * may a licensor, author or contributor be held liable for indirect,
18  * direct, other damage, loss, or other issues arising in any way out
19  * of dealing in the work, even if advised of the possibility of such
20  * damage or existence of a defect, except proven that it results out
21  * of said person's immediate fault when using the work as intended.
22  */
23
24 #include "sh.h"
25
26 __RCSID("$MirOS: src/bin/mksh/syn.c,v 1.124 2017/05/05 22:53:31 tg Exp $");
27
28 struct nesting_state {
29         int start_token;        /* token than began nesting (eg, FOR) */
30         int start_line;         /* line nesting began on */
31 };
32
33 struct yyrecursive_state {
34         struct ioword *old_heres[HERES];
35         struct yyrecursive_state *next;
36         struct ioword **old_herep;
37         int old_symbol;
38         int old_nesting_type;
39         bool old_reject;
40 };
41
42 static void yyparse(bool);
43 static struct op *pipeline(int, int);
44 static struct op *andor(int);
45 static struct op *c_list(int, bool);
46 static struct ioword *synio(int);
47 static struct op *nested(int, int, int, int);
48 static struct op *get_command(int, int);
49 static struct op *dogroup(int);
50 static struct op *thenpart(int);
51 static struct op *elsepart(int);
52 static struct op *caselist(int);
53 static struct op *casepart(int, int);
54 static struct op *function_body(char *, int, bool);
55 static char **wordlist(int);
56 static struct op *block(int, struct op *, struct op *);
57 static struct op *newtp(int);
58 static void syntaxerr(const char *) MKSH_A_NORETURN;
59 static void nesting_push(struct nesting_state *, int);
60 static void nesting_pop(struct nesting_state *);
61 static int inalias(struct source *) MKSH_A_PURE;
62 static Test_op dbtestp_isa(Test_env *, Test_meta);
63 static const char *dbtestp_getopnd(Test_env *, Test_op, bool);
64 static int dbtestp_eval(Test_env *, Test_op, const char *,
65     const char *, bool);
66 static void dbtestp_error(Test_env *, int, const char *) MKSH_A_NORETURN;
67
68 static struct op *outtree;              /* yyparse output */
69 static struct nesting_state nesting;    /* \n changed to ; */
70
71 static bool reject;                     /* token(cf) gets symbol again */
72 static int symbol;                      /* yylex value */
73
74 #define REJECT          (reject = true)
75 #define ACCEPT          (reject = false)
76 #define token(cf)       ((reject) ? (ACCEPT, symbol) : (symbol = yylex(cf)))
77 #define tpeek(cf)       ((reject) ? (symbol) : (REJECT, symbol = yylex(cf)))
78 #define musthave(c,cf)  do { if (token(cf) != (c)) syntaxerr(NULL); } while (/* CONSTCOND */ 0)
79
80 static const char Tcbrace[] = "}";
81 static const char Tesac[] = "esac";
82
83 static void
84 yyparse(bool doalias)
85 {
86         int c;
87
88         ACCEPT;
89
90         outtree = c_list(doalias ? ALIAS : 0, source->type == SSTRING);
91         c = tpeek(0);
92         if (c == 0 && !outtree)
93                 outtree = newtp(TEOF);
94         else if (!ctype(c, C_LF | C_NUL))
95                 syntaxerr(NULL);
96 }
97
98 static struct op *
99 pipeline(int cf, int sALIAS)
100 {
101         struct op *t, *p, *tl = NULL;
102
103         t = get_command(cf, sALIAS);
104         if (t != NULL) {
105                 while (token(0) == '|') {
106                         if ((p = get_command(CONTIN, sALIAS)) == NULL)
107                                 syntaxerr(NULL);
108                         if (tl == NULL)
109                                 t = tl = block(TPIPE, t, p);
110                         else
111                                 tl = tl->right = block(TPIPE, tl->right, p);
112                 }
113                 REJECT;
114         }
115         return (t);
116 }
117
118 static struct op *
119 andor(int sALIAS)
120 {
121         struct op *t, *p;
122         int c;
123
124         t = pipeline(0, sALIAS);
125         if (t != NULL) {
126                 while ((c = token(0)) == LOGAND || c == LOGOR) {
127                         if ((p = pipeline(CONTIN, sALIAS)) == NULL)
128                                 syntaxerr(NULL);
129                         t = block(c == LOGAND? TAND: TOR, t, p);
130                 }
131                 REJECT;
132         }
133         return (t);
134 }
135
136 static struct op *
137 c_list(int sALIAS, bool multi)
138 {
139         struct op *t = NULL, *p, *tl = NULL;
140         int c;
141         bool have_sep;
142
143         while (/* CONSTCOND */ 1) {
144                 p = andor(sALIAS);
145                 /*
146                  * Token has always been read/rejected at this point, so
147                  * we don't worry about what flags to pass token()
148                  */
149                 c = token(0);
150                 have_sep = true;
151                 if (c == '\n' && (multi || inalias(source))) {
152                         if (!p)
153                                 /* ignore blank lines */
154                                 continue;
155                 } else if (!p)
156                         break;
157                 else if (c == '&' || c == COPROC)
158                         p = block(c == '&' ? TASYNC : TCOPROC, p, NULL);
159                 else if (c != ';')
160                         have_sep = false;
161                 if (!t)
162                         t = p;
163                 else if (!tl)
164                         t = tl = block(TLIST, t, p);
165                 else
166                         tl = tl->right = block(TLIST, tl->right, p);
167                 if (!have_sep)
168                         break;
169         }
170         REJECT;
171         return (t);
172 }
173
174 static const char IONDELIM_delim[] = { CHAR, '<', CHAR, '<', EOS };
175
176 static struct ioword *
177 synio(int cf)
178 {
179         struct ioword *iop;
180         static struct ioword *nextiop;
181         bool ishere;
182
183         if (nextiop != NULL) {
184                 iop = nextiop;
185                 nextiop = NULL;
186                 return (iop);
187         }
188
189         if (tpeek(cf) != REDIR)
190                 return (NULL);
191         ACCEPT;
192         iop = yylval.iop;
193         ishere = (iop->ioflag & IOTYPE) == IOHERE;
194         if (iop->ioflag & IOHERESTR) {
195                 musthave(LWORD, 0);
196         } else if (ishere && tpeek(HEREDELIM) == '\n') {
197                 ACCEPT;
198                 yylval.cp = wdcopy(IONDELIM_delim, ATEMP);
199                 iop->ioflag |= IOEVAL | IONDELIM;
200         } else
201                 musthave(LWORD, ishere ? HEREDELIM : 0);
202         if (ishere) {
203                 iop->delim = yylval.cp;
204                 if (*ident != 0 && !(iop->ioflag & IOHERESTR)) {
205                         /* unquoted */
206                         iop->ioflag |= IOEVAL;
207                 }
208                 if (herep > &heres[HERES - 1])
209                         yyerror(Tf_toomany, "<<");
210                 *herep++ = iop;
211         } else
212                 iop->ioname = yylval.cp;
213
214         if (iop->ioflag & IOBASH) {
215                 char *cp;
216
217                 nextiop = alloc(sizeof(*iop), ATEMP);
218                 nextiop->ioname = cp = alloc(3, ATEMP);
219                 *cp++ = CHAR;
220                 *cp++ = digits_lc[iop->unit % 10];
221                 *cp = EOS;
222
223                 iop->ioflag &= ~IOBASH;
224                 nextiop->unit = 2;
225                 nextiop->ioflag = IODUP;
226                 nextiop->delim = NULL;
227                 nextiop->heredoc = NULL;
228         }
229         return (iop);
230 }
231
232 static struct op *
233 nested(int type, int smark, int emark, int sALIAS)
234 {
235         struct op *t;
236         struct nesting_state old_nesting;
237
238         nesting_push(&old_nesting, smark);
239         t = c_list(sALIAS, true);
240         musthave(emark, KEYWORD|sALIAS);
241         nesting_pop(&old_nesting);
242         return (block(type, t, NULL));
243 }
244
245 static const char builtin_cmd[] = {
246         QCHAR, '\\', CHAR, 'b', CHAR, 'u', CHAR, 'i',
247         CHAR, 'l', CHAR, 't', CHAR, 'i', CHAR, 'n', EOS
248 };
249 static const char let_cmd[] = {
250         CHAR, 'l', CHAR, 'e', CHAR, 't', EOS
251 };
252 static const char setA_cmd0[] = {
253         CHAR, 's', CHAR, 'e', CHAR, 't', EOS
254 };
255 static const char setA_cmd1[] = {
256         CHAR, '-', CHAR, 'A', EOS
257 };
258 static const char setA_cmd2[] = {
259         CHAR, '-', CHAR, '-', EOS
260 };
261
262 static struct op *
263 get_command(int cf, int sALIAS)
264 {
265         struct op *t;
266         int c, iopn = 0, syniocf, lno;
267         struct ioword *iop, **iops;
268         XPtrV args, vars;
269         struct nesting_state old_nesting;
270
271         /* NUFILE is small enough to leave this addition unchecked */
272         iops = alloc2((NUFILE + 1), sizeof(struct ioword *), ATEMP);
273         XPinit(args, 16);
274         XPinit(vars, 16);
275
276         syniocf = KEYWORD|sALIAS;
277         switch (c = token(cf|KEYWORD|sALIAS|CMDASN)) {
278         default:
279                 REJECT;
280                 afree(iops, ATEMP);
281                 XPfree(args);
282                 XPfree(vars);
283                 /* empty line */
284                 return (NULL);
285
286         case LWORD:
287         case REDIR:
288                 REJECT;
289                 syniocf &= ~(KEYWORD|sALIAS);
290                 t = newtp(TCOM);
291                 t->lineno = source->line;
292                 goto get_command_start;
293                 while (/* CONSTCOND */ 1) {
294                         bool check_decl_utility;
295
296                         if (XPsize(args) == 0) {
297  get_command_start:
298                                 check_decl_utility = true;
299                                 cf = sALIAS | CMDASN;
300                         } else if (t->u.evalflags)
301                                 cf = CMDWORD | CMDASN;
302                         else
303                                 cf = CMDWORD;
304                         switch (tpeek(cf)) {
305                         case REDIR:
306                                 while ((iop = synio(cf)) != NULL) {
307                                         if (iopn >= NUFILE)
308                                                 yyerror(Tf_toomany,
309                                                     Tredirection);
310                                         iops[iopn++] = iop;
311                                 }
312                                 break;
313
314                         case LWORD:
315                                 ACCEPT;
316                                 if (check_decl_utility) {
317                                         struct tbl *tt = get_builtin(ident);
318                                         uint32_t flag;
319
320                                         flag = tt ? tt->flag : 0;
321                                         if (flag & DECL_UTIL)
322                                                 t->u.evalflags = DOVACHECK;
323                                         if (!(flag & DECL_FWDR))
324                                                 check_decl_utility = false;
325                                 }
326                                 if ((XPsize(args) == 0 || Flag(FKEYWORD)) &&
327                                     is_wdvarassign(yylval.cp))
328                                         XPput(vars, yylval.cp);
329                                 else
330                                         XPput(args, yylval.cp);
331                                 break;
332
333                         case ord('(' /*)*/):
334                                 if (XPsize(args) == 0 && XPsize(vars) == 1 &&
335                                     is_wdvarassign(yylval.cp)) {
336                                         char *tcp;
337
338                                         /* wdarrassign: foo=(bar) */
339                                         ACCEPT;
340
341                                         /* manipulate the vars string */
342                                         tcp = XPptrv(vars)[(vars.len = 0)];
343                                         /* 'varname=' -> 'varname' */
344                                         tcp[wdscan(tcp, EOS) - tcp - 3] = EOS;
345
346                                         /* construct new args strings */
347                                         XPput(args, wdcopy(builtin_cmd, ATEMP));
348                                         XPput(args, wdcopy(setA_cmd0, ATEMP));
349                                         XPput(args, wdcopy(setA_cmd1, ATEMP));
350                                         XPput(args, tcp);
351                                         XPput(args, wdcopy(setA_cmd2, ATEMP));
352
353                                         /* slurp in words till closing paren */
354                                         while (token(CONTIN) == LWORD)
355                                                 XPput(args, yylval.cp);
356                                         if (symbol != /*(*/ ')')
357                                                 syntaxerr(NULL);
358                                 } else {
359                                         /*
360                                          * Check for "> foo (echo hi)"
361                                          * which AT&T ksh allows (not
362                                          * POSIX, but not disallowed)
363                                          */
364                                         afree(t, ATEMP);
365                                         if (XPsize(args) == 0 &&
366                                             XPsize(vars) == 0) {
367                                                 ACCEPT;
368                                                 goto Subshell;
369                                         }
370
371                                         /* must be a function */
372                                         if (iopn != 0 || XPsize(args) != 1 ||
373                                             XPsize(vars) != 0)
374                                                 syntaxerr(NULL);
375                                         ACCEPT;
376                                         musthave(/*(*/ ')', 0);
377                                         t = function_body(XPptrv(args)[0],
378                                             sALIAS, false);
379                                 }
380                                 goto Leave;
381
382                         default:
383                                 goto Leave;
384                         }
385                 }
386  Leave:
387                 break;
388
389         case ord('(' /*)*/): {
390                 int subshell_nesting_type_saved;
391  Subshell:
392                 subshell_nesting_type_saved = subshell_nesting_type;
393                 subshell_nesting_type = ord(')');
394                 t = nested(TPAREN, ord('('), ord(')'), sALIAS);
395                 subshell_nesting_type = subshell_nesting_type_saved;
396                 break;
397             }
398
399         case ord('{' /*}*/):
400                 t = nested(TBRACE, ord('{'), ord('}'), sALIAS);
401                 break;
402
403         case MDPAREN:
404                 /* leave KEYWORD in syniocf (allow if (( 1 )) then ...) */
405                 lno = source->line;
406                 ACCEPT;
407                 switch (token(LETEXPR)) {
408                 case LWORD:
409                         break;
410                 case ord('(' /*)*/):
411                         c = ord('(');
412                         goto Subshell;
413                 default:
414                         syntaxerr(NULL);
415                 }
416                 t = newtp(TCOM);
417                 t->lineno = lno;
418                 XPput(args, wdcopy(builtin_cmd, ATEMP));
419                 XPput(args, wdcopy(let_cmd, ATEMP));
420                 XPput(args, yylval.cp);
421                 break;
422
423         case DBRACKET: /* [[ .. ]] */
424                 /* leave KEYWORD in syniocf (allow if [[ -n 1 ]] then ...) */
425                 t = newtp(TDBRACKET);
426                 ACCEPT;
427                 {
428                         Test_env te;
429
430                         te.flags = TEF_DBRACKET;
431                         te.pos.av = &args;
432                         te.isa = dbtestp_isa;
433                         te.getopnd = dbtestp_getopnd;
434                         te.eval = dbtestp_eval;
435                         te.error = dbtestp_error;
436
437                         test_parse(&te);
438                 }
439                 break;
440
441         case FOR:
442         case SELECT:
443                 t = newtp((c == FOR) ? TFOR : TSELECT);
444                 musthave(LWORD, CMDASN);
445                 if (!is_wdvarname(yylval.cp, true))
446                         yyerror("%s: bad identifier",
447                             c == FOR ? "for" : Tselect);
448                 strdupx(t->str, ident, ATEMP);
449                 nesting_push(&old_nesting, c);
450                 t->vars = wordlist(sALIAS);
451                 t->left = dogroup(sALIAS);
452                 nesting_pop(&old_nesting);
453                 break;
454
455         case WHILE:
456         case UNTIL:
457                 nesting_push(&old_nesting, c);
458                 t = newtp((c == WHILE) ? TWHILE : TUNTIL);
459                 t->left = c_list(sALIAS, true);
460                 t->right = dogroup(sALIAS);
461                 nesting_pop(&old_nesting);
462                 break;
463
464         case CASE:
465                 t = newtp(TCASE);
466                 musthave(LWORD, 0);
467                 t->str = yylval.cp;
468                 nesting_push(&old_nesting, c);
469                 t->left = caselist(sALIAS);
470                 nesting_pop(&old_nesting);
471                 break;
472
473         case IF:
474                 nesting_push(&old_nesting, c);
475                 t = newtp(TIF);
476                 t->left = c_list(sALIAS, true);
477                 t->right = thenpart(sALIAS);
478                 musthave(FI, KEYWORD|sALIAS);
479                 nesting_pop(&old_nesting);
480                 break;
481
482         case BANG:
483                 syniocf &= ~(KEYWORD|sALIAS);
484                 t = pipeline(0, sALIAS);
485                 if (t == NULL)
486                         syntaxerr(NULL);
487                 t = block(TBANG, NULL, t);
488                 break;
489
490         case TIME:
491                 syniocf &= ~(KEYWORD|sALIAS);
492                 t = pipeline(0, sALIAS);
493                 if (t && t->type == TCOM) {
494                         t->str = alloc(2, ATEMP);
495                         /* TF_* flags */
496                         t->str[0] = '\0';
497                         t->str[1] = '\0';
498                 }
499                 t = block(TTIME, t, NULL);
500                 break;
501
502         case FUNCTION:
503                 musthave(LWORD, 0);
504                 t = function_body(yylval.cp, sALIAS, true);
505                 break;
506         }
507
508         while ((iop = synio(syniocf)) != NULL) {
509                 if (iopn >= NUFILE)
510                         yyerror(Tf_toomany, Tredirection);
511                 iops[iopn++] = iop;
512         }
513
514         if (iopn == 0) {
515                 afree(iops, ATEMP);
516                 t->ioact = NULL;
517         } else {
518                 iops[iopn++] = NULL;
519                 iops = aresize2(iops, iopn, sizeof(struct ioword *), ATEMP);
520                 t->ioact = iops;
521         }
522
523         if (t->type == TCOM || t->type == TDBRACKET) {
524                 XPput(args, NULL);
525                 t->args = (const char **)XPclose(args);
526                 XPput(vars, NULL);
527                 t->vars = (char **)XPclose(vars);
528         } else {
529                 XPfree(args);
530                 XPfree(vars);
531         }
532
533         if (c == MDPAREN) {
534                 t = block(TBRACE, t, NULL);
535                 t->ioact = t->left->ioact;
536                 t->left->ioact = NULL;
537         }
538
539         return (t);
540 }
541
542 static struct op *
543 dogroup(int sALIAS)
544 {
545         int c;
546         struct op *list;
547
548         c = token(CONTIN|KEYWORD|sALIAS);
549         /*
550          * A {...} can be used instead of do...done for for/select loops
551          * but not for while/until loops - we don't need to check if it
552          * is a while loop because it would have been parsed as part of
553          * the conditional command list...
554          */
555         if (c == DO)
556                 c = DONE;
557         else if (c == ord('{'))
558                 c = ord('}');
559         else
560                 syntaxerr(NULL);
561         list = c_list(sALIAS, true);
562         musthave(c, KEYWORD|sALIAS);
563         return (list);
564 }
565
566 static struct op *
567 thenpart(int sALIAS)
568 {
569         struct op *t;
570
571         musthave(THEN, KEYWORD|sALIAS);
572         t = newtp(0);
573         t->left = c_list(sALIAS, true);
574         if (t->left == NULL)
575                 syntaxerr(NULL);
576         t->right = elsepart(sALIAS);
577         return (t);
578 }
579
580 static struct op *
581 elsepart(int sALIAS)
582 {
583         struct op *t;
584
585         switch (token(KEYWORD|sALIAS|CMDASN)) {
586         case ELSE:
587                 if ((t = c_list(sALIAS, true)) == NULL)
588                         syntaxerr(NULL);
589                 return (t);
590
591         case ELIF:
592                 t = newtp(TELIF);
593                 t->left = c_list(sALIAS, true);
594                 t->right = thenpart(sALIAS);
595                 return (t);
596
597         default:
598                 REJECT;
599         }
600         return (NULL);
601 }
602
603 static struct op *
604 caselist(int sALIAS)
605 {
606         struct op *t, *tl;
607         int c;
608
609         c = token(CONTIN|KEYWORD|sALIAS);
610         /* A {...} can be used instead of in...esac for case statements */
611         if (c == IN)
612                 c = ESAC;
613         else if (c == ord('{'))
614                 c = ord('}');
615         else
616                 syntaxerr(NULL);
617         t = tl = NULL;
618         /* no ALIAS here */
619         while ((tpeek(CONTIN|KEYWORD|ESACONLY)) != c) {
620                 struct op *tc = casepart(c, sALIAS);
621                 if (tl == NULL)
622                         t = tl = tc, tl->right = NULL;
623                 else
624                         tl->right = tc, tl = tc;
625         }
626         musthave(c, KEYWORD|sALIAS);
627         return (t);
628 }
629
630 static struct op *
631 casepart(int endtok, int sALIAS)
632 {
633         struct op *t;
634         XPtrV ptns;
635
636         XPinit(ptns, 16);
637         t = newtp(TPAT);
638         /* no ALIAS here */
639         if (token(CONTIN | KEYWORD) != ord('('))
640                 REJECT;
641         do {
642                 switch (token(0)) {
643                 case LWORD:
644                         break;
645                 case ord('}'):
646                 case ESAC:
647                         if (symbol != endtok) {
648                                 strdupx(yylval.cp,
649                                     symbol == ord('}') ? Tcbrace : Tesac,
650                                     ATEMP);
651                                 break;
652                         }
653                         /* FALLTHROUGH */
654                 default:
655                         syntaxerr(NULL);
656                 }
657                 XPput(ptns, yylval.cp);
658         } while (token(0) == '|');
659         REJECT;
660         XPput(ptns, NULL);
661         t->vars = (char **)XPclose(ptns);
662         musthave(ord(')'), 0);
663
664         t->left = c_list(sALIAS, true);
665
666         /* initialise to default for ;; or omitted */
667         t->u.charflag = ord(';');
668         /* SUSv4 requires the ;; except in the last casepart */
669         if ((tpeek(CONTIN|KEYWORD|sALIAS)) != endtok)
670                 switch (symbol) {
671                 default:
672                         syntaxerr(NULL);
673                 case BRKEV:
674                         t->u.charflag = ord('|');
675                         if (0)
676                                 /* FALLTHROUGH */
677                 case BRKFT:
678                           t->u.charflag = ord('&');
679                         /* FALLTHROUGH */
680                 case BREAK:
681                         /* initialised above, but we need to eat the token */
682                         ACCEPT;
683                 }
684         return (t);
685 }
686
687 static struct op *
688 function_body(char *name, int sALIAS,
689     /* function foo { ... } vs foo() { .. } */
690     bool ksh_func)
691 {
692         char *sname, *p;
693         struct op *t;
694
695         sname = wdstrip(name, 0);
696         /*-
697          * Check for valid characters in name. POSIX and AT&T ksh93 say
698          * only allow [a-zA-Z_0-9] but this allows more as old pdkshs
699          * have allowed more; the following were never allowed:
700          *      NUL TAB NL SP " $ & ' ( ) ; < = > \ ` |
701          * C_QUOTE|C_SPC covers all but adds # * ? [ ]
702          */
703         for (p = sname; *p; p++)
704                 if (ctype(*p, C_QUOTE | C_SPC))
705                         yyerror(Tinvname, sname, Tfunction);
706
707         /*
708          * Note that POSIX allows only compound statements after foo(),
709          * sh and AT&T ksh allow any command, go with the later since it
710          * shouldn't break anything. However, for function foo, AT&T ksh
711          * only accepts an open-brace.
712          */
713         if (ksh_func) {
714                 if (tpeek(CONTIN|KEYWORD|sALIAS) == ord('(' /*)*/)) {
715                         /* function foo () { //}*/
716                         ACCEPT;
717                         musthave(ord(/*(*/ ')'), 0);
718                         /* degrade to POSIX function */
719                         ksh_func = false;
720                 }
721                 musthave(ord('{' /*}*/), CONTIN|KEYWORD|sALIAS);
722                 REJECT;
723         }
724
725         t = newtp(TFUNCT);
726         t->str = sname;
727         t->u.ksh_func = tobool(ksh_func);
728         t->lineno = source->line;
729
730         if ((t->left = get_command(CONTIN, sALIAS)) == NULL) {
731                 char *tv;
732                 /*
733                  * Probably something like foo() followed by EOF or ';'.
734                  * This is accepted by sh and ksh88.
735                  * To make "typeset -f foo" work reliably (so its output can
736                  * be used as input), we pretend there is a colon here.
737                  */
738                 t->left = newtp(TCOM);
739                 /* (2 * sizeof(char *)) is small enough */
740                 t->left->args = alloc(2 * sizeof(char *), ATEMP);
741                 t->left->args[0] = tv = alloc(3, ATEMP);
742                 tv[0] = QCHAR;
743                 tv[1] = ':';
744                 tv[2] = EOS;
745                 t->left->args[1] = NULL;
746                 t->left->vars = alloc(sizeof(char *), ATEMP);
747                 t->left->vars[0] = NULL;
748                 t->left->lineno = 1;
749         }
750
751         return (t);
752 }
753
754 static char **
755 wordlist(int sALIAS)
756 {
757         int c;
758         XPtrV args;
759
760         XPinit(args, 16);
761         /* POSIX does not do alias expansion here... */
762         if ((c = token(CONTIN|KEYWORD|sALIAS)) != IN) {
763                 if (c != ';')
764                         /* non-POSIX, but AT&T ksh accepts a ; here */
765                         REJECT;
766                 return (NULL);
767         }
768         while ((c = token(0)) == LWORD)
769                 XPput(args, yylval.cp);
770         if (c != '\n' && c != ';')
771                 syntaxerr(NULL);
772         XPput(args, NULL);
773         return ((char **)XPclose(args));
774 }
775
776 /*
777  * supporting functions
778  */
779
780 static struct op *
781 block(int type, struct op *t1, struct op *t2)
782 {
783         struct op *t;
784
785         t = newtp(type);
786         t->left = t1;
787         t->right = t2;
788         return (t);
789 }
790
791 static const struct tokeninfo {
792         const char *name;
793         short val;
794         short reserved;
795 } tokentab[] = {
796         /* Reserved words */
797         { "if",         IF,     true },
798         { "then",       THEN,   true },
799         { "else",       ELSE,   true },
800         { "elif",       ELIF,   true },
801         { "fi",         FI,     true },
802         { "case",       CASE,   true },
803         { Tesac,        ESAC,   true },
804         { "for",        FOR,    true },
805         { Tselect,      SELECT, true },
806         { "while",      WHILE,  true },
807         { "until",      UNTIL,  true },
808         { "do",         DO,     true },
809         { "done",       DONE,   true },
810         { "in",         IN,     true },
811         { Tfunction,    FUNCTION, true },
812         { Ttime,        TIME,   true },
813         { "{",          ord('{'), true },
814         { Tcbrace,      ord('}'), true },
815         { "!",          BANG,   true },
816         { "[[",         DBRACKET, true },
817         /* Lexical tokens (0[EOF], LWORD and REDIR handled specially) */
818         { "&&",         LOGAND, false },
819         { "||",         LOGOR,  false },
820         { ";;",         BREAK,  false },
821         { ";|",         BRKEV,  false },
822         { ";&",         BRKFT,  false },
823         { "((",         MDPAREN, false },
824         { "|&",         COPROC, false },
825         /* and some special cases... */
826         { "newline",    ord('\n'), false },
827         { NULL,         0,      false }
828 };
829
830 void
831 initkeywords(void)
832 {
833         struct tokeninfo const *tt;
834         struct tbl *p;
835
836         ktinit(APERM, &keywords,
837             /* currently 28 keywords: 75% of 64 = 2^6 */
838             6);
839         for (tt = tokentab; tt->name; tt++) {
840                 if (tt->reserved) {
841                         p = ktenter(&keywords, tt->name, hash(tt->name));
842                         p->flag |= DEFINED|ISSET;
843                         p->type = CKEYWD;
844                         p->val.i = tt->val;
845                 }
846         }
847 }
848
849 static void
850 syntaxerr(const char *what)
851 {
852         /* 23<<- is the longest redirection, I think */
853         char redir[8];
854         const char *s;
855         struct tokeninfo const *tt;
856         int c;
857
858         if (!what)
859                 what = Tunexpected;
860         REJECT;
861         c = token(0);
862  Again:
863         switch (c) {
864         case 0:
865                 if (nesting.start_token) {
866                         c = nesting.start_token;
867                         source->errline = nesting.start_line;
868                         what = "unmatched";
869                         goto Again;
870                 }
871                 /* don't quote the EOF */
872                 yyerror("%s: unexpected EOF", Tsynerr);
873                 /* NOTREACHED */
874
875         case LWORD:
876                 s = snptreef(NULL, 32, Tf_S, yylval.cp);
877                 break;
878
879         case REDIR:
880                 s = snptreef(redir, sizeof(redir), Tft_R, yylval.iop);
881                 break;
882
883         default:
884                 for (tt = tokentab; tt->name; tt++)
885                         if (tt->val == c)
886                             break;
887                 if (tt->name)
888                         s = tt->name;
889                 else {
890                         if (c > 0 && c < 256) {
891                                 redir[0] = c;
892                                 redir[1] = '\0';
893                         } else
894                                 shf_snprintf(redir, sizeof(redir),
895                                         "?%d", c);
896                         s = redir;
897                 }
898         }
899         yyerror(Tf_sD_s_qs, Tsynerr, what, s);
900 }
901
902 static void
903 nesting_push(struct nesting_state *save, int tok)
904 {
905         *save = nesting;
906         nesting.start_token = tok;
907         nesting.start_line = source->line;
908 }
909
910 static void
911 nesting_pop(struct nesting_state *saved)
912 {
913         nesting = *saved;
914 }
915
916 static struct op *
917 newtp(int type)
918 {
919         struct op *t;
920
921         t = alloc(sizeof(struct op), ATEMP);
922         t->type = type;
923         t->u.evalflags = 0;
924         t->args = NULL;
925         t->vars = NULL;
926         t->ioact = NULL;
927         t->left = t->right = NULL;
928         t->str = NULL;
929         return (t);
930 }
931
932 struct op *
933 compile(Source *s, bool skiputf8bom, bool doalias)
934 {
935         nesting.start_token = 0;
936         nesting.start_line = 0;
937         herep = heres;
938         source = s;
939         if (skiputf8bom)
940                 yyskiputf8bom();
941         yyparse(doalias);
942         return (outtree);
943 }
944
945 /* Check if we are in the middle of reading an alias */
946 static int
947 inalias(struct source *s)
948 {
949         while (s && s->type == SALIAS) {
950                 if (!(s->flags & SF_ALIASEND))
951                         return (1);
952                 s = s->next;
953         }
954         return (0);
955 }
956
957
958 /*
959  * Order important - indexed by Test_meta values
960  * Note that ||, &&, ( and ) can't appear in as unquoted strings
961  * in normal shell input, so these can be interpreted unambiguously
962  * in the evaluation pass.
963  */
964 static const char dbtest_or[] = { CHAR, '|', CHAR, '|', EOS };
965 static const char dbtest_and[] = { CHAR, '&', CHAR, '&', EOS };
966 static const char dbtest_not[] = { CHAR, '!', EOS };
967 static const char dbtest_oparen[] = { CHAR, '(', EOS };
968 static const char dbtest_cparen[] = { CHAR, ')', EOS };
969 const char * const dbtest_tokens[] = {
970         dbtest_or, dbtest_and, dbtest_not,
971         dbtest_oparen, dbtest_cparen
972 };
973 static const char db_close[] = { CHAR, ']', CHAR, ']', EOS };
974 static const char db_lthan[] = { CHAR, '<', EOS };
975 static const char db_gthan[] = { CHAR, '>', EOS };
976
977 /*
978  * Test if the current token is a whatever. Accepts the current token if
979  * it is. Returns 0 if it is not, non-zero if it is (in the case of
980  * TM_UNOP and TM_BINOP, the returned value is a Test_op).
981  */
982 static Test_op
983 dbtestp_isa(Test_env *te, Test_meta meta)
984 {
985         int c = tpeek(CMDASN | (meta == TM_BINOP ? 0 : CONTIN));
986         bool uqword;
987         char *save = NULL;
988         Test_op ret = TO_NONOP;
989
990         /* unquoted word? */
991         uqword = c == LWORD && *ident;
992
993         if (meta == TM_OR)
994                 ret = c == LOGOR ? TO_NONNULL : TO_NONOP;
995         else if (meta == TM_AND)
996                 ret = c == LOGAND ? TO_NONNULL : TO_NONOP;
997         else if (meta == TM_NOT)
998                 ret = (uqword && !strcmp(yylval.cp,
999                     dbtest_tokens[(int)TM_NOT])) ? TO_NONNULL : TO_NONOP;
1000         else if (meta == TM_OPAREN)
1001                 ret = c == ord('(') /*)*/ ? TO_NONNULL : TO_NONOP;
1002         else if (meta == TM_CPAREN)
1003                 ret = c == /*(*/ ord(')') ? TO_NONNULL : TO_NONOP;
1004         else if (meta == TM_UNOP || meta == TM_BINOP) {
1005                 if (meta == TM_BINOP && c == REDIR &&
1006                     (yylval.iop->ioflag == IOREAD ||
1007                     yylval.iop->ioflag == IOWRITE)) {
1008                         ret = TO_NONNULL;
1009                         save = wdcopy(yylval.iop->ioflag == IOREAD ?
1010                             db_lthan : db_gthan, ATEMP);
1011                 } else if (uqword && (ret = test_isop(meta, ident)))
1012                         save = yylval.cp;
1013         } else
1014                 /* meta == TM_END */
1015                 ret = (uqword && !strcmp(yylval.cp,
1016                     db_close)) ? TO_NONNULL : TO_NONOP;
1017         if (ret != TO_NONOP) {
1018                 ACCEPT;
1019                 if ((unsigned int)meta < NELEM(dbtest_tokens))
1020                         save = wdcopy(dbtest_tokens[(int)meta], ATEMP);
1021                 if (save)
1022                         XPput(*te->pos.av, save);
1023         }
1024         return (ret);
1025 }
1026
1027 static const char *
1028 dbtestp_getopnd(Test_env *te, Test_op op MKSH_A_UNUSED,
1029     bool do_eval MKSH_A_UNUSED)
1030 {
1031         int c = tpeek(CMDASN);
1032
1033         if (c != LWORD)
1034                 return (NULL);
1035
1036         ACCEPT;
1037         XPput(*te->pos.av, yylval.cp);
1038
1039         return (null);
1040 }
1041
1042 static int
1043 dbtestp_eval(Test_env *te MKSH_A_UNUSED, Test_op op MKSH_A_UNUSED,
1044     const char *opnd1 MKSH_A_UNUSED, const char *opnd2 MKSH_A_UNUSED,
1045     bool do_eval MKSH_A_UNUSED)
1046 {
1047         return (1);
1048 }
1049
1050 static void
1051 dbtestp_error(Test_env *te, int offset, const char *msg)
1052 {
1053         te->flags |= TEF_ERROR;
1054
1055         if (offset < 0) {
1056                 REJECT;
1057                 /* Kludgy to say the least... */
1058                 symbol = LWORD;
1059                 yylval.cp = *(XPptrv(*te->pos.av) + XPsize(*te->pos.av) +
1060                     offset);
1061         }
1062         syntaxerr(msg);
1063 }
1064
1065 #if HAVE_SELECT
1066
1067 #ifndef EOVERFLOW
1068 #ifdef ERANGE
1069 #define EOVERFLOW       ERANGE
1070 #else
1071 #define EOVERFLOW       EINVAL
1072 #endif
1073 #endif
1074
1075 bool
1076 parse_usec(const char *s, struct timeval *tv)
1077 {
1078         struct timeval tt;
1079         int i;
1080
1081         tv->tv_sec = 0;
1082         /* parse integral part */
1083         while (ctype(*s, C_DIGIT)) {
1084                 tt.tv_sec = tv->tv_sec * 10 + ksh_numdig(*s++);
1085                 /*XXX this overflow check maybe UB */
1086                 if (tt.tv_sec / 10 != tv->tv_sec) {
1087                         errno = EOVERFLOW;
1088                         return (true);
1089                 }
1090                 tv->tv_sec = tt.tv_sec;
1091         }
1092
1093         tv->tv_usec = 0;
1094         if (!*s)
1095                 /* no decimal fraction */
1096                 return (false);
1097         else if (*s++ != '.') {
1098                 /* junk after integral part */
1099                 errno = EINVAL;
1100                 return (true);
1101         }
1102
1103         /* parse decimal fraction */
1104         i = 100000;
1105         while (ctype(*s, C_DIGIT)) {
1106                 tv->tv_usec += i * ksh_numdig(*s++);
1107                 if (i == 1)
1108                         break;
1109                 i /= 10;
1110         }
1111         /* check for junk after fractional part */
1112         while (ctype(*s, C_DIGIT))
1113                 ++s;
1114         if (*s) {
1115                 errno = EINVAL;
1116                 return (true);
1117         }
1118
1119         /* end of input string reached, no errors */
1120         return (false);
1121 }
1122 #endif
1123
1124 /*
1125  * Helper function called from within lex.c:yylex() to parse
1126  * a COMSUB recursively using the main shell parser and lexer
1127  */
1128 char *
1129 yyrecursive(int subtype)
1130 {
1131         struct op *t;
1132         char *cp;
1133         struct yyrecursive_state *ys;
1134         int stok, etok;
1135
1136         if (subtype != COMSUB) {
1137                 stok = ord('{');
1138                 etok = ord('}');
1139         } else {
1140                 stok = ord('(');
1141                 etok = ord(')');
1142         }
1143
1144         ys = alloc(sizeof(struct yyrecursive_state), ATEMP);
1145
1146         /* tell the lexer to accept a closing parenthesis as EOD */
1147         ys->old_nesting_type = subshell_nesting_type;
1148         subshell_nesting_type = etok;
1149
1150         /* push reject state, parse recursively, pop reject state */
1151         ys->old_reject = reject;
1152         ys->old_symbol = symbol;
1153         ACCEPT;
1154         memcpy(ys->old_heres, heres, sizeof(heres));
1155         ys->old_herep = herep;
1156         herep = heres;
1157         ys->next = e->yyrecursive_statep;
1158         e->yyrecursive_statep = ys;
1159         /* we use TPAREN as a helper container here */
1160         t = nested(TPAREN, stok, etok, ALIAS);
1161         yyrecursive_pop(false);
1162
1163         /* t->left because nested(TPAREN, ...) hides our goodies there */
1164         cp = snptreef(NULL, 0, Tf_T, t->left);
1165         tfree(t, ATEMP);
1166
1167         return (cp);
1168 }
1169
1170 void
1171 yyrecursive_pop(bool popall)
1172 {
1173         struct yyrecursive_state *ys;
1174
1175  popnext:
1176         if (!(ys = e->yyrecursive_statep))
1177                 return;
1178         e->yyrecursive_statep = ys->next;
1179
1180         memcpy(heres, ys->old_heres, sizeof(heres));
1181         herep = ys->old_herep;
1182         reject = ys->old_reject;
1183         symbol = ys->old_symbol;
1184
1185         subshell_nesting_type = ys->old_nesting_type;
1186
1187         afree(ys, ATEMP);
1188         if (popall)
1189                 goto popnext;
1190 }