3c37c73eb54665762257ea5d4bc3abb4f6701bcc
[platform/upstream/bash.git] / parse.y
1 /* Yacc grammar for bash. */
2
3 /* Copyright (C) 1989 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 2, or (at your option) any later
10    version.
11
12    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
13    WARRANTY; without even the implied warranty of MERCHANTABILITY or
14    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15    for more details.
16
17    You should have received a copy of the GNU General Public License along
18    with Bash; see the file LICENSE.  If not, write to the Free Software
19    Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
20
21 %{
22 #include "config.h"
23
24 #include "bashtypes.h"
25 #include "bashansi.h"
26
27 #if defined (HAVE_UNISTD_H)
28 #  include <unistd.h>
29 #endif
30
31 #if defined (HAVE_LOCALE_H)
32 #  include <locale.h>
33 #endif
34
35 #include <stdio.h>
36 #include <signal.h>
37
38 #include "memalloc.h"
39
40 #include "shell.h"
41 #include "trap.h"
42 #include "flags.h"
43 #include "parser.h"
44 #include "mailcheck.h"
45 #include "builtins/common.h"
46 #include "builtins/builtext.h"
47
48 #if defined (READLINE)
49 #  include "bashline.h"
50 #  include <readline/readline.h>
51 #endif /* READLINE */
52
53 #if defined (HISTORY)
54 #  include "bashhist.h"
55 #  include <readline/history.h>
56 #endif /* HISTORY */
57
58 #if defined (JOB_CONTROL)
59 #  include "jobs.h"
60 #endif /* JOB_CONTROL */
61
62 #if defined (ALIAS)
63 #  include "alias.h"
64 #endif /* ALIAS */
65
66 #if defined (PROMPT_STRING_DECODE)
67 #  ifndef _MINIX
68 #    include <sys/param.h>
69 #  endif
70 #  include <time.h>
71 #  include "maxpath.h"
72 #endif /* PROMPT_STRING_DECODE */
73
74 #define RE_READ_TOKEN   -99
75 #define NO_EXPANSION    -100
76
77 #define YYDEBUG 0
78
79 #if defined (EXTENDED_GLOB)
80 #define PATTERN_CHAR(c) \
81         ((c) == '@' || (c) == '*' || (c) == '+' || (c) == '?' || (c) == '!')
82
83 extern int extended_glob;
84 #endif
85
86 extern int eof_encountered;
87 extern int no_line_editing, running_under_emacs;
88 extern int current_command_number;
89 extern int interactive, interactive_shell, login_shell;
90 extern int sourcelevel;
91 extern int posixly_correct;
92 extern int last_command_exit_value;
93 extern int interrupt_immediately;
94 extern char *shell_name, *current_host_name;
95 extern char *dist_version;
96 extern int patch_level;
97 extern int dump_translatable_strings, dump_po_strings;
98 extern Function *last_shell_builtin, *this_shell_builtin;
99 #if defined (BUFFERED_INPUT)
100 extern int bash_input_fd_changed;
101 #endif
102
103 extern int errno;
104 /* **************************************************************** */
105 /*                                                                  */
106 /*                  "Forward" declarations                          */
107 /*                                                                  */
108 /* **************************************************************** */
109
110 static char *ansiexpand ();
111 static char *localeexpand ();
112 static int reserved_word_acceptable ();
113 static int read_token ();
114 static int yylex ();
115 static int parse_arith_cmd ();
116 #if defined (COND_COMMAND)
117 static COMMAND *parse_cond_command ();
118 #endif
119 static int read_token_word ();
120 static void discard_parser_constructs ();
121
122 static void report_syntax_error ();
123 static void handle_eof_input_unit ();
124 static void prompt_again ();
125 #if 0
126 static void reset_readline_prompt ();
127 #endif
128 static void print_prompt ();
129
130 extern int yyerror ();
131
132 /* Default prompt strings */
133 char *primary_prompt = PPROMPT;
134 char *secondary_prompt = SPROMPT;
135
136 /* PROMPT_STRING_POINTER points to one of these, never to an actual string. */
137 char *ps1_prompt, *ps2_prompt;
138
139 /* Handle on the current prompt string.  Indirectly points through
140    ps1_ or ps2_prompt. */
141 char **prompt_string_pointer = (char **)NULL;
142 char *current_prompt_string;
143
144 /* Non-zero means we expand aliases in commands. */
145 int expand_aliases = 0;
146
147 /* If non-zero, the decoded prompt string undergoes parameter and
148    variable substitution, command substitution, arithmetic substitution,
149    string expansion, process substitution, and quote removal in
150    decode_prompt_string. */
151 int promptvars = 1;
152
153 /* The decoded prompt string.  Used if READLINE is not defined or if
154    editing is turned off.  Analogous to current_readline_prompt. */
155 static char *current_decoded_prompt;
156
157 /* The number of lines read from input while creating the current command. */
158 int current_command_line_count;
159
160 /* Variables to manage the task of reading here documents, because we need to
161    defer the reading until after a complete command has been collected. */
162 static REDIRECT *redir_stack[10];
163 int need_here_doc;
164
165 /* Where shell input comes from.  History expansion is performed on each
166    line when the shell is interactive. */
167 static char *shell_input_line = (char *)NULL;
168 static int shell_input_line_index;
169 static int shell_input_line_size;       /* Amount allocated for shell_input_line. */
170 static int shell_input_line_len;        /* strlen (shell_input_line) */
171
172 /* Either zero or EOF. */
173 static int shell_input_line_terminator;
174
175 /* The line number in a script on which a function definition starts. */
176 static int function_dstart;
177
178 /* The line number in a script on which a function body starts. */
179 static int function_bstart;
180
181 /* The line number in a script at which an arithmetic for command starts. */
182 static int arith_for_lineno;
183
184 static REDIRECTEE redir;
185 %}
186
187 %union {
188   WORD_DESC *word;              /* the word that we read. */
189   int number;                   /* the number that we read. */
190   WORD_LIST *word_list;
191   COMMAND *command;
192   REDIRECT *redirect;
193   ELEMENT element;
194   PATTERN_LIST *pattern;
195 }
196
197 /* Reserved words.  Members of the first group are only recognized
198    in the case that they are preceded by a list_terminator.  Members
199    of the second group are for [[...]] commands.  Members of the
200    third group are recognized only under special circumstances. */
201 %token IF THEN ELSE ELIF FI CASE ESAC FOR SELECT WHILE UNTIL DO DONE FUNCTION
202 %token COND_START COND_END COND_ERROR
203 %token IN BANG TIME TIMEOPT
204
205 /* More general tokens. yylex () knows how to make these. */
206 %token <word> WORD ASSIGNMENT_WORD
207 %token <number> NUMBER
208 %token <word_list> ARITH_CMD ARITH_FOR_EXPRS
209 %token <command> COND_CMD
210 %token AND_AND OR_OR GREATER_GREATER LESS_LESS LESS_AND
211 %token GREATER_AND SEMI_SEMI LESS_LESS_MINUS AND_GREATER LESS_GREATER
212 %token GREATER_BAR
213
214 /* The types that the various syntactical units return. */
215
216 %type <command> inputunit command pipeline pipeline_command
217 %type <command> list list0 list1 compound_list simple_list simple_list1
218 %type <command> simple_command shell_command
219 %type <command> for_command select_command case_command group_command
220 %type <command> arith_command
221 %type <command> cond_command
222 %type <command> arith_for_command
223 %type <command> function_def if_command elif_clause subshell
224 %type <redirect> redirection redirection_list
225 %type <element> simple_command_element
226 %type <word_list> word_list pattern
227 %type <pattern> pattern_list case_clause_sequence case_clause
228 %type <number> timespec
229
230 %start inputunit
231
232 %left '&' ';' '\n' yacc_EOF
233 %left AND_AND OR_OR
234 %right '|'
235 %%
236
237 inputunit:      simple_list '\n'
238                         {
239                           /* Case of regular command.  Discard the error
240                              safety net,and return the command just parsed. */
241                           global_command = $1;
242                           eof_encountered = 0;
243                           discard_parser_constructs (0);
244                           YYACCEPT;
245                         }
246         |       '\n'
247                         {
248                           /* Case of regular command, but not a very
249                              interesting one.  Return a NULL command. */
250                           global_command = (COMMAND *)NULL;
251                           YYACCEPT;
252                         }
253         |       error '\n'
254                         {
255                           /* Error during parsing.  Return NULL command. */
256                           global_command = (COMMAND *)NULL;
257                           eof_encountered = 0;
258                           discard_parser_constructs (1);
259                           if (interactive)
260                             {
261                               YYACCEPT;
262                             }
263                           else
264                             {
265                               YYABORT;
266                             }
267                         }
268         |       yacc_EOF
269                         {
270                           /* Case of EOF seen by itself.  Do ignoreeof or
271                              not. */
272                           global_command = (COMMAND *)NULL;
273                           handle_eof_input_unit ();
274                           YYACCEPT;
275                         }
276         ;
277
278 word_list:      WORD
279                         { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
280         |       word_list WORD
281                         { $$ = make_word_list ($2, $1); }
282         ;
283
284 redirection:    '>' WORD
285                         {
286                           redir.filename = $2;
287                           $$ = make_redirection (1, r_output_direction, redir);
288                         }
289         |       '<' WORD
290                         {
291                           redir.filename = $2;
292                           $$ = make_redirection (0, r_input_direction, redir);
293                         }
294         |       NUMBER '>' WORD
295                         {
296                           redir.filename = $3;
297                           $$ = make_redirection ($1, r_output_direction, redir);
298                         }
299         |       NUMBER '<' WORD
300                         {
301                           redir.filename = $3;
302                           $$ = make_redirection ($1, r_input_direction, redir);
303                         }
304         |       GREATER_GREATER WORD
305                         {
306                           redir.filename = $2;
307                           $$ = make_redirection (1, r_appending_to, redir);
308                         }
309         |       NUMBER GREATER_GREATER WORD
310                         {
311                           redir.filename = $3;
312                           $$ = make_redirection ($1, r_appending_to, redir);
313                         }
314         |       LESS_LESS WORD
315                         {
316                           redir.filename = $2;
317                           $$ = make_redirection (0, r_reading_until, redir);
318                           redir_stack[need_here_doc++] = $$;
319                         }
320         |       NUMBER LESS_LESS WORD
321                         {
322                           redir.filename = $3;
323                           $$ = make_redirection ($1, r_reading_until, redir);
324                           redir_stack[need_here_doc++] = $$;
325                         }
326         |       LESS_AND NUMBER
327                         {
328                           redir.dest = $2;
329                           $$ = make_redirection (0, r_duplicating_input, redir);
330                         }
331         |       NUMBER LESS_AND NUMBER
332                         {
333                           redir.dest = $3;
334                           $$ = make_redirection ($1, r_duplicating_input, redir);
335                         }
336         |       GREATER_AND NUMBER
337                         {
338                           redir.dest = $2;
339                           $$ = make_redirection (1, r_duplicating_output, redir);
340                         }
341         |       NUMBER GREATER_AND NUMBER
342                         {
343                           redir.dest = $3;
344                           $$ = make_redirection ($1, r_duplicating_output, redir);
345                         }
346         |       LESS_AND WORD
347                         {
348                           redir.filename = $2;
349                           $$ = make_redirection (0, r_duplicating_input_word, redir);
350                         }
351         |       NUMBER LESS_AND WORD
352                         {
353                           redir.filename = $3;
354                           $$ = make_redirection ($1, r_duplicating_input_word, redir);
355                         }
356         |       GREATER_AND WORD
357                         {
358                           redir.filename = $2;
359                           $$ = make_redirection (1, r_duplicating_output_word, redir);
360                         }
361         |       NUMBER GREATER_AND WORD
362                         {
363                           redir.filename = $3;
364                           $$ = make_redirection ($1, r_duplicating_output_word, redir);
365                         }
366         |       LESS_LESS_MINUS WORD
367                         {
368                           redir.filename = $2;
369                           $$ = make_redirection
370                             (0, r_deblank_reading_until, redir);
371                           redir_stack[need_here_doc++] = $$;
372                         }
373         |       NUMBER LESS_LESS_MINUS WORD
374                         {
375                           redir.filename = $3;
376                           $$ = make_redirection
377                             ($1, r_deblank_reading_until, redir);
378                           redir_stack[need_here_doc++] = $$;
379                         }
380         |       GREATER_AND '-'
381                         {
382                           redir.dest = 0L;
383                           $$ = make_redirection (1, r_close_this, redir);
384                         }
385         |       NUMBER GREATER_AND '-'
386                         {
387                           redir.dest = 0L;
388                           $$ = make_redirection ($1, r_close_this, redir);
389                         }
390         |       LESS_AND '-'
391                         {
392                           redir.dest = 0L;
393                           $$ = make_redirection (0, r_close_this, redir);
394                         }
395         |       NUMBER LESS_AND '-'
396                         {
397                           redir.dest = 0L;
398                           $$ = make_redirection ($1, r_close_this, redir);
399                         }
400         |       AND_GREATER WORD
401                         {
402                           redir.filename = $2;
403                           $$ = make_redirection (1, r_err_and_out, redir);
404                         }
405         |       NUMBER LESS_GREATER WORD
406                         {
407                           redir.filename = $3;
408                           $$ = make_redirection ($1, r_input_output, redir);
409                         }
410         |       LESS_GREATER WORD
411                         {
412                           redir.filename = $2;
413                           $$ = make_redirection (0, r_input_output, redir);
414                         }
415         |       GREATER_BAR WORD
416                         {
417                           redir.filename = $2;
418                           $$ = make_redirection (1, r_output_force, redir);
419                         }
420         |       NUMBER GREATER_BAR WORD
421                         {
422                           redir.filename = $3;
423                           $$ = make_redirection ($1, r_output_force, redir);
424                         }
425         ;
426
427 simple_command_element: WORD
428                         { $$.word = $1; $$.redirect = 0; }
429         |       ASSIGNMENT_WORD
430                         { $$.word = $1; $$.redirect = 0; }
431         |       redirection
432                         { $$.redirect = $1; $$.word = 0; }
433         ;
434
435 redirection_list: redirection
436                         {
437                           $$ = $1;
438                         }
439         |       redirection_list redirection
440                         {
441                           register REDIRECT *t;
442
443                           for (t = $1; t->next; t = t->next)
444                             ;
445                           t->next = $2;
446                           $$ = $1;
447                         }
448         ;
449
450 simple_command: simple_command_element
451                         { $$ = make_simple_command ($1, (COMMAND *)NULL); }
452         |       simple_command simple_command_element
453                         { $$ = make_simple_command ($2, $1); }
454         ;
455
456 command:        simple_command
457                         { $$ = clean_simple_command ($1); }
458         |       shell_command
459                         { $$ = $1; }
460         |       shell_command redirection_list
461                         {
462                           COMMAND *tc;
463
464                           tc = $1;
465                           /* According to Posix.2 3.9.5, redirections
466                              specified after the body of a function should
467                              be attached to the function and performed when
468                              the function is executed, not as part of the
469                              function definition command. */
470                           /* XXX - I don't think it matters, but we might
471                              want to change this in the future to avoid
472                              problems differentiating between a function
473                              definition with a redirection and a function
474                              definition containing a single command with a
475                              redirection.  The two are semantically equivalent,
476                              though -- the only difference is in how the
477                              command printing code displays the redirections. */
478                           if (tc->type == cm_function_def)
479                             {
480                               tc = tc->value.Function_def->command;
481                               if (tc->type == cm_group)
482                                 tc = tc->value.Group->command;
483                             }
484                           if (tc->redirects)
485                             {
486                               register REDIRECT *t;
487                               for (t = tc->redirects; t->next; t = t->next)
488                                 ;
489                               t->next = $2;
490                             }
491                           else
492                             tc->redirects = $2;
493                           $$ = $1;
494                         }
495         ;
496
497 shell_command:  for_command
498                         { $$ = $1; }
499         |       case_command
500                         { $$ = $1; }
501         |       WHILE compound_list DO compound_list DONE
502                         { $$ = make_while_command ($2, $4); }
503         |       UNTIL compound_list DO compound_list DONE
504                         { $$ = make_until_command ($2, $4); }
505         |       select_command
506                         { $$ = $1; }
507         |       if_command
508                         { $$ = $1; }
509         |       subshell
510                         { $$ = $1; }
511         |       group_command
512                         { $$ = $1; }
513         |       arith_command
514                         { $$ = $1; }
515         |       cond_command
516                         { $$ = $1; }
517         |       arith_for_command
518                         { $$ = $1; }
519         |       function_def
520                         { $$ = $1; }
521         ;
522
523 for_command:    FOR WORD newline_list DO compound_list DONE
524                         { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5); }
525         |       FOR WORD newline_list '{' compound_list '}'
526                         { $$ = make_for_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5); }
527         |       FOR WORD ';' newline_list DO compound_list DONE
528                         { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
529         |       FOR WORD ';' newline_list '{' compound_list '}'
530                         { $$ = make_for_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6); }
531         |       FOR WORD newline_list IN word_list list_terminator newline_list DO compound_list DONE
532                         { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
533         |       FOR WORD newline_list IN word_list list_terminator newline_list '{' compound_list '}'
534                         { $$ = make_for_command ($2, REVERSE_LIST ($5, WORD_LIST *), $9); }
535         ;
536
537 arith_for_command:      FOR ARITH_FOR_EXPRS list_terminator newline_list DO compound_list DONE
538                                 { $$ = make_arith_for_command ($2, $6, arith_for_lineno); }
539         |               FOR ARITH_FOR_EXPRS list_terminator newline_list '{' compound_list '}'
540                                 { $$ = make_arith_for_command ($2, $6, arith_for_lineno); }
541         ;
542 select_command: SELECT WORD newline_list DO list DONE
543                         {
544                           $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $5);
545                         }
546         |       SELECT WORD newline_list '{' list '}'
547                         {
548                           $$ = make_select_command ($2, add_string_to_list ("$@", (WORD_LIST *)NULL), $5);
549                         }
550         |       SELECT WORD ';' newline_list DO list DONE
551                         {
552                           $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
553                         }
554         |       SELECT WORD ';' newline_list '{' list '}'
555                         {
556                           $$ = make_select_command ($2, add_string_to_list ("\"$@\"", (WORD_LIST *)NULL), $6);
557                         }
558         |       SELECT WORD newline_list IN word_list list_terminator newline_list DO list DONE
559                         {
560                           $$ = make_select_command ($2, (WORD_LIST *)reverse_list ($5), $9);
561                         }
562         |       SELECT WORD newline_list IN word_list list_terminator newline_list '{' list '}'
563                         {
564                           $$ = make_select_command ($2, (WORD_LIST *)reverse_list ($5), $9);
565                         }
566         ;
567
568 case_command:   CASE WORD newline_list IN newline_list ESAC
569                         { $$ = make_case_command ($2, (PATTERN_LIST *)NULL); }
570         |       CASE WORD newline_list IN case_clause_sequence newline_list ESAC
571                         { $$ = make_case_command ($2, $5); }
572         |       CASE WORD newline_list IN case_clause ESAC
573                         { $$ = make_case_command ($2, $5); }
574         ;
575
576 function_def:   WORD '(' ')' newline_list group_command
577                         { $$ = make_function_def ($1, $5, function_dstart, function_bstart); }
578
579
580         |       FUNCTION WORD '(' ')' newline_list group_command
581                         { $$ = make_function_def ($2, $6, function_dstart, function_bstart); }
582
583         |       FUNCTION WORD newline_list group_command
584                         { $$ = make_function_def ($2, $4, function_dstart, function_bstart); }
585         ;
586
587 subshell:       '(' compound_list ')'
588                         {
589                           $$ = make_subshell_command ($2);
590                           $$->flags |= CMD_WANT_SUBSHELL;
591                         }
592         ;
593
594 if_command:     IF compound_list THEN compound_list FI
595                         { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
596         |       IF compound_list THEN compound_list ELSE compound_list FI
597                         { $$ = make_if_command ($2, $4, $6); }
598         |       IF compound_list THEN compound_list elif_clause FI
599                         { $$ = make_if_command ($2, $4, $5); }
600         ;
601
602
603 group_command:  '{' list '}'
604                         { $$ = make_group_command ($2); }
605         ;
606
607 arith_command:  ARITH_CMD
608                         { $$ = make_arith_command ($1); }
609         ;
610
611 cond_command:   COND_START COND_CMD COND_END
612                         { $$ = $2; }
613         ; 
614
615 elif_clause:    ELIF compound_list THEN compound_list
616                         { $$ = make_if_command ($2, $4, (COMMAND *)NULL); }
617         |       ELIF compound_list THEN compound_list ELSE compound_list
618                         { $$ = make_if_command ($2, $4, $6); }
619         |       ELIF compound_list THEN compound_list elif_clause
620                         { $$ = make_if_command ($2, $4, $5); }
621         ;
622
623 case_clause:    pattern_list
624         |       case_clause_sequence pattern_list
625                         { $2->next = $1; $$ = $2; }
626         ;
627
628 pattern_list:   newline_list pattern ')' compound_list
629                         { $$ = make_pattern_list ($2, $4); }
630         |       newline_list pattern ')' newline_list
631                         { $$ = make_pattern_list ($2, (COMMAND *)NULL); }
632         |       newline_list '(' pattern ')' compound_list
633                         { $$ = make_pattern_list ($3, $5); }
634         |       newline_list '(' pattern ')' newline_list
635                         { $$ = make_pattern_list ($3, (COMMAND *)NULL); }
636         ;
637
638 case_clause_sequence:  pattern_list SEMI_SEMI
639         |       case_clause_sequence pattern_list SEMI_SEMI
640                         { $2->next = $1; $$ = $2; }
641         ;
642
643 pattern:        WORD
644                         { $$ = make_word_list ($1, (WORD_LIST *)NULL); }
645         |       pattern '|' WORD
646                         { $$ = make_word_list ($3, $1); }
647         ;
648
649 /* A list allows leading or trailing newlines and
650    newlines as operators (equivalent to semicolons).
651    It must end with a newline or semicolon.
652    Lists are used within commands such as if, for, while.  */
653
654 list:           newline_list list0
655                         {
656                           $$ = $2;
657                           if (need_here_doc)
658                             gather_here_documents ();
659                          }
660         ;
661
662 compound_list:  list
663         |       newline_list list1
664                         {
665                           $$ = $2;
666                         }
667         ;
668
669 list0:          list1 '\n' newline_list
670         |       list1 '&' newline_list
671                         {
672                           if ($1->type == cm_connection)
673                             $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
674                           else
675                             $$ = command_connect ($1, (COMMAND *)NULL, '&');
676                         }
677         |       list1 ';' newline_list
678
679         ;
680
681 list1:          list1 AND_AND newline_list list1
682                         { $$ = command_connect ($1, $4, AND_AND); }
683         |       list1 OR_OR newline_list list1
684                         { $$ = command_connect ($1, $4, OR_OR); }
685         |       list1 '&' newline_list list1
686                         {
687                           if ($1->type == cm_connection)
688                             $$ = connect_async_list ($1, $4, '&');
689                           else
690                             $$ = command_connect ($1, $4, '&');
691                         }
692         |       list1 ';' newline_list list1
693                         { $$ = command_connect ($1, $4, ';'); }
694         |       list1 '\n' newline_list list1
695                         { $$ = command_connect ($1, $4, ';'); }
696         |       pipeline_command
697                         { $$ = $1; }
698         ;
699
700 list_terminator:'\n'
701         |       ';'
702         |       yacc_EOF
703         ;
704
705 newline_list:
706         |       newline_list '\n'
707         ;
708
709 /* A simple_list is a list that contains no significant newlines
710    and no leading or trailing newlines.  Newlines are allowed
711    only following operators, where they are not significant.
712
713    This is what an inputunit consists of.  */
714
715 simple_list:    simple_list1
716                         {
717                           $$ = $1;
718                           if (need_here_doc)
719                             gather_here_documents ();
720                         }
721         |       simple_list1 '&'
722                         {
723                           if ($1->type == cm_connection)
724                             $$ = connect_async_list ($1, (COMMAND *)NULL, '&');
725                           else
726                             $$ = command_connect ($1, (COMMAND *)NULL, '&');
727                           if (need_here_doc)
728                             gather_here_documents ();
729                         }
730         |       simple_list1 ';'
731                         {
732                           $$ = $1;
733                           if (need_here_doc)
734                             gather_here_documents ();
735                         }
736         ;
737
738 simple_list1:   simple_list1 AND_AND newline_list simple_list1
739                         { $$ = command_connect ($1, $4, AND_AND); }
740         |       simple_list1 OR_OR newline_list simple_list1
741                         { $$ = command_connect ($1, $4, OR_OR); }
742         |       simple_list1 '&' simple_list1
743                         {
744                           if ($1->type == cm_connection)
745                             $$ = connect_async_list ($1, $3, '&');
746                           else
747                             $$ = command_connect ($1, $3, '&');
748                         }
749         |       simple_list1 ';' simple_list1
750                         { $$ = command_connect ($1, $3, ';'); }
751
752         |       pipeline_command
753                         { $$ = $1; }
754         ;
755
756 pipeline_command: pipeline
757                         { $$ = $1; }
758         |       BANG pipeline
759                         {
760                           $2->flags |= CMD_INVERT_RETURN;
761                           $$ = $2;
762                         }
763         |       timespec pipeline
764                         {
765                           $2->flags |= $1;
766                           $$ = $2;
767                         }
768         |       timespec BANG pipeline
769                         {
770                           $3->flags |= $1|CMD_INVERT_RETURN;
771                           $$ = $3;
772                         }
773         |       BANG timespec pipeline
774                         {
775                           $3->flags |= $2|CMD_INVERT_RETURN;
776                           $$ = $3;
777                         }
778         ;
779
780 pipeline:
781                 pipeline '|' newline_list pipeline
782                         { $$ = command_connect ($1, $4, '|'); }
783         |       command
784                         { $$ = $1; }
785         ;
786
787 timespec:       TIME
788                         { $$ = CMD_TIME_PIPELINE; }
789         |       TIME TIMEOPT
790                         { $$ = CMD_TIME_PIPELINE|CMD_TIME_POSIX; }
791         ;
792 %%
793
794 /* Possible states for the parser that require it to do special things. */
795 #define PST_CASEPAT     0x001           /* in a case pattern list */
796 #define PST_ALEXPNEXT   0x002           /* expand next word for aliases */
797 #define PST_ALLOWOPNBRC 0x004           /* allow open brace for function def */
798 #define PST_NEEDCLOSBRC 0x008           /* need close brace */
799 #define PST_DBLPAREN    0x010           /* double-paren parsing */
800 #define PST_SUBSHELL    0x020           /* ( ... ) subshell */
801 #define PST_CMDSUBST    0x040           /* $( ... ) command substitution */
802 #define PST_CASESTMT    0x080           /* parsing a case statement */
803 #define PST_CONDCMD     0x100           /* parsing a [[...]] command */
804 #define PST_CONDEXPR    0x200           /* parsing the guts of [[...]] */
805 #define PST_ARITHFOR    0x400           /* parsing an arithmetic for command */
806
807 /* Initial size to allocate for tokens, and the
808    amount to grow them by. */
809 #define TOKEN_DEFAULT_INITIAL_SIZE 496
810 #define TOKEN_DEFAULT_GROW_SIZE 512
811
812 /* Shell meta-characters that, when unquoted, separate words. */
813 #define shellmeta(c)    (strchr (shell_meta_chars, (c)) != 0)
814 #define shellbreak(c)   (strchr (shell_break_chars, (c)) != 0)
815 #define shellquote(c)   ((c) == '"' || (c) == '`' || (c) == '\'')
816 #define shellexp(c)     ((c) == '$' || (c) == '<' || (c) == '>')
817
818 char *shell_meta_chars = "()<>;&|";
819 char *shell_break_chars = "()<>;&| \t\n";
820
821 /* The token currently being read. */
822 static int current_token;
823
824 /* The last read token, or NULL.  read_token () uses this for context
825    checking. */
826 static int last_read_token;
827
828 /* The token read prior to last_read_token. */
829 static int token_before_that;
830
831 /* The token read prior to token_before_that. */
832 static int two_tokens_ago;
833
834 /* If non-zero, it is the token that we want read_token to return
835    regardless of what text is (or isn't) present to be read.  This
836    is reset by read_token.  If token_to_read == WORD or
837    ASSIGNMENT_WORD, yylval.word should be set to word_desc_to_read. */
838 static int token_to_read;
839 static WORD_DESC *word_desc_to_read;
840
841 /* The current parser state. */
842 static int parser_state;
843
844 /* Global var is non-zero when end of file has been reached. */
845 int EOF_Reached = 0;
846
847 void
848 debug_parser (i)
849      int i;
850 {
851 #if YYDEBUG != 0
852   yydebug = i;
853 #endif
854 }
855
856 /* yy_getc () returns the next available character from input or EOF.
857    yy_ungetc (c) makes `c' the next character to read.
858    init_yy_io (get, unget, type, location) makes the function GET the
859    installed function for getting the next character, makes UNGET the
860    installed function for un-getting a character, sets the type of stream
861    (either string or file) from TYPE, and makes LOCATION point to where
862    the input is coming from. */
863
864 /* Unconditionally returns end-of-file. */
865 int
866 return_EOF ()
867 {
868   return (EOF);
869 }
870
871 /* Variable containing the current get and unget functions.
872    See ./input.h for a clearer description. */
873 BASH_INPUT bash_input;
874
875 /* Set all of the fields in BASH_INPUT to NULL.  Free bash_input.name if it
876    is non-null, avoiding a memory leak. */
877 void
878 initialize_bash_input ()
879 {
880   bash_input.type = st_none;
881   FREE (bash_input.name);
882   bash_input.name = (char *)NULL;
883   bash_input.location.file = (FILE *)NULL;
884   bash_input.location.string = (char *)NULL;
885   bash_input.getter = (Function *)NULL;
886   bash_input.ungetter = (Function *)NULL;
887 }
888
889 /* Set the contents of the current bash input stream from
890    GET, UNGET, TYPE, NAME, and LOCATION. */
891 void
892 init_yy_io (get, unget, type, name, location)
893      Function *get, *unget;
894      enum stream_type type;
895      char *name;
896      INPUT_STREAM location;
897 {
898   bash_input.type = type;
899   FREE (bash_input.name);
900   bash_input.name = name ? savestring (name) : (char *)NULL;
901
902   /* XXX */
903 #if defined (CRAY)
904   memcpy((char *)&bash_input.location.string, (char *)&location.string, sizeof(location));
905 #else
906   bash_input.location = location;
907 #endif
908   bash_input.getter = get;
909   bash_input.ungetter = unget;
910 }
911
912 /* Call this to get the next character of input. */
913 int
914 yy_getc ()
915 {
916   return (*(bash_input.getter)) ();
917 }
918
919 /* Call this to unget C.  That is, to make C the next character
920    to be read. */
921 int
922 yy_ungetc (c)
923      int c;
924 {
925   return (*(bash_input.ungetter)) (c);
926 }
927
928 #if defined (BUFFERED_INPUT)
929 int
930 input_file_descriptor ()
931 {
932   switch (bash_input.type)
933     {
934     case st_stream:
935       return (fileno (bash_input.location.file));
936     case st_bstream:
937       return (bash_input.location.buffered_fd);
938     case st_stdin:
939     default:
940       return (fileno (stdin));
941     }
942 }
943 #endif /* BUFFERED_INPUT */
944
945 /* **************************************************************** */
946 /*                                                                  */
947 /*                Let input be read from readline ().               */
948 /*                                                                  */
949 /* **************************************************************** */
950
951 #if defined (READLINE)
952 char *current_readline_prompt = (char *)NULL;
953 char *current_readline_line = (char *)NULL;
954 int current_readline_line_index = 0;
955
956 static int
957 yy_readline_get ()
958 {
959   SigHandler *old_sigint;
960   int line_len, c;
961
962   if (!current_readline_line)
963     {
964       if (!bash_readline_initialized)
965         initialize_readline ();
966
967 #if defined (JOB_CONTROL)
968       if (job_control)
969         give_terminal_to (shell_pgrp);
970 #endif /* JOB_CONTROL */
971
972       if (signal_is_ignored (SIGINT) == 0)
973         {
974           old_sigint = (SigHandler *)set_signal_handler (SIGINT, sigint_sighandler);
975           interrupt_immediately++;
976         }
977
978       current_readline_line = readline (current_readline_prompt ?
979                                           current_readline_prompt : "");
980
981       if (signal_is_ignored (SIGINT) == 0)
982         {
983           interrupt_immediately--;
984           set_signal_handler (SIGINT, old_sigint);
985         }
986
987 #if 0
988       /* Reset the prompt to the decoded value of prompt_string_pointer. */
989       reset_readline_prompt ();
990 #endif
991
992       if (current_readline_line == 0)
993         return (EOF);
994
995       current_readline_line_index = 0;
996       line_len = strlen (current_readline_line);
997
998       current_readline_line = xrealloc (current_readline_line, 2 + line_len);
999       current_readline_line[line_len++] = '\n';
1000       current_readline_line[line_len] = '\0';
1001     }
1002
1003   if (current_readline_line[current_readline_line_index] == 0)
1004     {
1005       free (current_readline_line);
1006       current_readline_line = (char *)NULL;
1007       return (yy_readline_get ());
1008     }
1009   else
1010     {
1011       c = (unsigned char)current_readline_line[current_readline_line_index++];
1012       return (c);
1013     }
1014 }
1015
1016 static int
1017 yy_readline_unget (c)
1018      int c;
1019 {
1020   if (current_readline_line_index && current_readline_line)
1021     current_readline_line[--current_readline_line_index] = c;
1022   return (c);
1023 }
1024
1025 void
1026 with_input_from_stdin ()
1027 {
1028   INPUT_STREAM location;
1029
1030   if (bash_input.type != st_stdin && stream_on_stack (st_stdin) == 0)
1031     {
1032       location.string = current_readline_line;
1033       init_yy_io (yy_readline_get, yy_readline_unget,
1034                   st_stdin, "readline stdin", location);
1035     }
1036 }
1037
1038 #else  /* !READLINE */
1039
1040 void
1041 with_input_from_stdin ()
1042 {
1043   with_input_from_stream (stdin, "stdin");
1044 }
1045 #endif  /* !READLINE */
1046
1047 /* **************************************************************** */
1048 /*                                                                  */
1049 /*   Let input come from STRING.  STRING is zero terminated.        */
1050 /*                                                                  */
1051 /* **************************************************************** */
1052
1053 static int
1054 yy_string_get ()
1055 {
1056   register char *string;
1057   register int c;
1058
1059   string = bash_input.location.string;
1060   c = EOF;
1061
1062   /* If the string doesn't exist, or is empty, EOF found. */
1063   if (string && *string)
1064     {
1065       c = *(unsigned char *)string++;
1066       bash_input.location.string = string;
1067     }
1068   return (c);
1069 }
1070
1071 static int
1072 yy_string_unget (c)
1073      int c;
1074 {
1075   *(--bash_input.location.string) = c;
1076   return (c);
1077 }
1078
1079 void
1080 with_input_from_string (string, name)
1081      char *string, *name;
1082 {
1083   INPUT_STREAM location;
1084
1085   location.string = string;
1086   init_yy_io (yy_string_get, yy_string_unget, st_string, name, location);
1087 }
1088
1089 /* **************************************************************** */
1090 /*                                                                  */
1091 /*                   Let input come from STREAM.                    */
1092 /*                                                                  */
1093 /* **************************************************************** */
1094
1095 /* These two functions used to test the value of the HAVE_RESTARTABLE_SYSCALLS
1096    define, and just use getc/ungetc if it was defined, but since bash
1097    installs its signal handlers without the SA_RESTART flag, some signals
1098    (like SIGCHLD, SIGWINCH, etc.) received during a read(2) will not cause
1099    the read to be restarted.  We need to restart it ourselves. */
1100
1101 static int
1102 yy_stream_get ()
1103 {
1104   int result;
1105
1106   result = EOF;
1107   if (bash_input.location.file)
1108     result = getc_with_restart (bash_input.location.file);
1109
1110   return (result);
1111 }
1112
1113 static int
1114 yy_stream_unget (c)
1115      int c;
1116 {
1117   return (ungetc_with_restart (c, bash_input.location.file));
1118 }
1119
1120 void
1121 with_input_from_stream (stream, name)
1122      FILE *stream;
1123      char *name;
1124 {
1125   INPUT_STREAM location;
1126
1127   location.file = stream;
1128   init_yy_io (yy_stream_get, yy_stream_unget, st_stream, name, location);
1129 }
1130
1131 typedef struct stream_saver {
1132   struct stream_saver *next;
1133   BASH_INPUT bash_input;
1134   int line;
1135 #if defined (BUFFERED_INPUT)
1136   BUFFERED_STREAM *bstream;
1137 #endif /* BUFFERED_INPUT */
1138 } STREAM_SAVER;
1139
1140 /* The globally known line number. */
1141 int line_number = 0;
1142
1143 #if defined (COND_COMMAND)
1144 static int cond_lineno;
1145 static int cond_token;
1146 #endif
1147
1148 STREAM_SAVER *stream_list = (STREAM_SAVER *)NULL;
1149
1150 void
1151 push_stream (reset_lineno)
1152      int reset_lineno;
1153 {
1154   STREAM_SAVER *saver = (STREAM_SAVER *)xmalloc (sizeof (STREAM_SAVER));
1155
1156   xbcopy ((char *)&bash_input, (char *)&(saver->bash_input), sizeof (BASH_INPUT));
1157
1158 #if defined (BUFFERED_INPUT)
1159   saver->bstream = (BUFFERED_STREAM *)NULL;
1160   /* If we have a buffered stream, clear out buffers[fd]. */
1161   if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1162     saver->bstream = set_buffered_stream (bash_input.location.buffered_fd,
1163                                           (BUFFERED_STREAM *)NULL);
1164 #endif /* BUFFERED_INPUT */
1165
1166   saver->line = line_number;
1167   bash_input.name = (char *)NULL;
1168   saver->next = stream_list;
1169   stream_list = saver;
1170   EOF_Reached = 0;
1171   if (reset_lineno)
1172     line_number = 0;
1173 }
1174
1175 void
1176 pop_stream ()
1177 {
1178   if (!stream_list)
1179     EOF_Reached = 1;
1180   else
1181     {
1182       STREAM_SAVER *saver = stream_list;
1183
1184       EOF_Reached = 0;
1185       stream_list = stream_list->next;
1186
1187       init_yy_io (saver->bash_input.getter,
1188                   saver->bash_input.ungetter,
1189                   saver->bash_input.type,
1190                   saver->bash_input.name,
1191                   saver->bash_input.location);
1192
1193 #if defined (BUFFERED_INPUT)
1194       /* If we have a buffered stream, restore buffers[fd]. */
1195       /* If the input file descriptor was changed while this was on the
1196          save stack, update the buffered fd to the new file descriptor and
1197          re-establish the buffer <-> bash_input fd correspondence. */
1198       if (bash_input.type == st_bstream && bash_input.location.buffered_fd >= 0)
1199         {
1200           if (bash_input_fd_changed)
1201             {
1202               bash_input_fd_changed = 0;
1203               if (default_buffered_input >= 0)
1204                 {
1205                   bash_input.location.buffered_fd = default_buffered_input;
1206                   saver->bstream->b_fd = default_buffered_input;
1207                 }
1208             }
1209           set_buffered_stream (bash_input.location.buffered_fd, saver->bstream);
1210         }
1211 #endif /* BUFFERED_INPUT */
1212
1213       line_number = saver->line;
1214
1215       FREE (saver->bash_input.name);
1216       free (saver);
1217     }
1218 }
1219
1220 /* Return 1 if a stream of type TYPE is saved on the stack. */
1221 int
1222 stream_on_stack (type)
1223      enum stream_type type;
1224 {
1225   register STREAM_SAVER *s;
1226
1227   for (s = stream_list; s; s = s->next)
1228     if (s->bash_input.type == type)
1229       return 1;
1230   return 0;
1231 }
1232
1233 /* Save the current token state and return it in a malloced array. */
1234 int *
1235 save_token_state ()
1236 {
1237   int *ret;
1238
1239   ret = (int *)xmalloc (3 * sizeof (int));
1240   ret[0] = last_read_token;
1241   ret[1] = token_before_that;
1242   ret[2] = two_tokens_ago;
1243   return ret;
1244 }
1245
1246 void
1247 restore_token_state (ts)
1248      int *ts;
1249 {
1250   if (ts == 0)
1251     return;
1252   last_read_token = ts[0];
1253   token_before_that = ts[1];
1254   two_tokens_ago = ts[2];
1255 }
1256
1257 /*
1258  * This is used to inhibit alias expansion and reserved word recognition
1259  * inside case statement pattern lists.  A `case statement pattern list' is:
1260  *
1261  *      everything between the `in' in a `case word in' and the next ')'
1262  *      or `esac'
1263  *      everything between a `;;' and the next `)' or `esac'
1264  */
1265
1266 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1267
1268 #if !defined (ALIAS)
1269 typedef void *alias_t;
1270 #endif
1271
1272 #define END_OF_ALIAS 0
1273
1274 /*
1275  * Pseudo-global variables used in implementing token-wise alias expansion.
1276  */
1277
1278 /*
1279  * Pushing and popping strings.  This works together with shell_getc to
1280  * implement alias expansion on a per-token basis.
1281  */
1282
1283 typedef struct string_saver {
1284   struct string_saver *next;
1285   int expand_alias;  /* Value to set expand_alias to when string is popped. */
1286   char *saved_line;
1287 #if defined (ALIAS)
1288   alias_t *expander;   /* alias that caused this line to be pushed. */
1289 #endif
1290   int saved_line_size, saved_line_index, saved_line_terminator;
1291 } STRING_SAVER;
1292
1293 STRING_SAVER *pushed_string_list = (STRING_SAVER *)NULL;
1294
1295 /*
1296  * Push the current shell_input_line onto a stack of such lines and make S
1297  * the current input.  Used when expanding aliases.  EXPAND is used to set
1298  * the value of expand_next_token when the string is popped, so that the
1299  * word after the alias in the original line is handled correctly when the
1300  * alias expands to multiple words.  TOKEN is the token that was expanded
1301  * into S; it is saved and used to prevent infinite recursive expansion.
1302  */
1303 static void
1304 push_string (s, expand, ap)
1305      char *s;
1306      int expand;
1307      alias_t *ap;
1308 {
1309   STRING_SAVER *temp = (STRING_SAVER *) xmalloc (sizeof (STRING_SAVER));
1310
1311   temp->expand_alias = expand;
1312   temp->saved_line = shell_input_line;
1313   temp->saved_line_size = shell_input_line_size;
1314   temp->saved_line_index = shell_input_line_index;
1315   temp->saved_line_terminator = shell_input_line_terminator;
1316 #if defined (ALIAS)
1317   temp->expander = ap;
1318 #endif
1319   temp->next = pushed_string_list;
1320   pushed_string_list = temp;
1321
1322 #if defined (ALIAS)
1323   if (ap)
1324     ap->flags |= AL_BEINGEXPANDED;
1325 #endif
1326
1327   shell_input_line = s;
1328   shell_input_line_size = strlen (s);
1329   shell_input_line_index = 0;
1330   shell_input_line_terminator = '\0';
1331   parser_state &= ~PST_ALEXPNEXT;
1332 }
1333
1334 /*
1335  * Make the top of the pushed_string stack be the current shell input.
1336  * Only called when there is something on the stack.  Called from shell_getc
1337  * when it thinks it has consumed the string generated by an alias expansion
1338  * and needs to return to the original input line.
1339  */
1340 static void
1341 pop_string ()
1342 {
1343   STRING_SAVER *t;
1344
1345   FREE (shell_input_line);
1346   shell_input_line = pushed_string_list->saved_line;
1347   shell_input_line_index = pushed_string_list->saved_line_index;
1348   shell_input_line_size = pushed_string_list->saved_line_size;
1349   shell_input_line_terminator = pushed_string_list->saved_line_terminator;
1350
1351   if (pushed_string_list->expand_alias)
1352     parser_state |= PST_ALEXPNEXT;
1353   else
1354     parser_state &= ~PST_ALEXPNEXT;
1355
1356   t = pushed_string_list;
1357   pushed_string_list = pushed_string_list->next;
1358
1359 #if defined (ALIAS)
1360   if (t->expander)
1361     t->expander->flags &= ~AL_BEINGEXPANDED;
1362 #endif
1363
1364   free ((char *)t);
1365 }
1366
1367 static void
1368 free_string_list ()
1369 {
1370   register STRING_SAVER *t, *t1;
1371
1372   for (t = pushed_string_list; t; )
1373     {
1374       t1 = t->next;
1375       FREE (t->saved_line);
1376 #if defined (ALIAS)
1377       if (t->expander)
1378         t->expander->flags &= ~AL_BEINGEXPANDED;
1379 #endif
1380       free ((char *)t);
1381       t = t1;
1382     }
1383   pushed_string_list = (STRING_SAVER *)NULL;
1384 }
1385
1386 #endif /* ALIAS || DPAREN_ARITHMETIC */
1387
1388 /* Return a line of text, taken from wherever yylex () reads input.
1389    If there is no more input, then we return NULL.  If REMOVE_QUOTED_NEWLINE
1390    is non-zero, we remove unquoted \<newline> pairs.  This is used by
1391    read_secondary_line to read here documents. */
1392 static char *
1393 read_a_line (remove_quoted_newline)
1394      int remove_quoted_newline;
1395 {
1396   static char *line_buffer = (char *)NULL;
1397   static int buffer_size = 0;
1398   int indx = 0, c, peekc, pass_next;
1399
1400 #if defined (READLINE)
1401   if (interactive && bash_input.type != st_string && no_line_editing)
1402 #else
1403   if (interactive && bash_input.type != st_string)
1404 #endif
1405     print_prompt ();
1406
1407   pass_next = 0;
1408   while (1)
1409     {
1410       c = yy_getc ();
1411
1412       /* Allow immediate exit if interrupted during input. */
1413       QUIT;
1414
1415       if (c == 0)
1416         continue;
1417
1418       /* If there is no more input, then we return NULL. */
1419       if (c == EOF)
1420         {
1421           if (interactive && bash_input.type == st_stream)
1422             clearerr (stdin);
1423           if (indx == 0)
1424             return ((char *)NULL);
1425           c = '\n';
1426         }
1427
1428       /* `+2' in case the final character in the buffer is a newline. */
1429       RESIZE_MALLOCED_BUFFER (line_buffer, indx, 2, buffer_size, 128);
1430
1431       /* IF REMOVE_QUOTED_NEWLINES is non-zero, we are reading a
1432          here document with an unquoted delimiter.  In this case,
1433          the line will be expanded as if it were in double quotes.
1434          We allow a backslash to escape the next character, but we
1435          need to treat the backslash specially only if a backslash
1436          quoting a backslash-newline pair appears in the line. */
1437       if (pass_next)
1438         {
1439           line_buffer[indx++] = c;
1440           pass_next = 0;
1441         }
1442       else if (c == '\\' && remove_quoted_newline)
1443         {
1444           peekc = yy_getc ();
1445           if (peekc == '\n')
1446             continue;   /* Make the unquoted \<newline> pair disappear. */
1447           else
1448             {
1449               yy_ungetc (peekc);
1450               pass_next = 1;
1451               line_buffer[indx++] = c;          /* Preserve the backslash. */
1452             }
1453         }
1454       else
1455         line_buffer[indx++] = c;
1456
1457       if (c == '\n')
1458         {
1459           line_buffer[indx] = '\0';
1460           return (line_buffer);
1461         }
1462     }
1463 }
1464
1465 /* Return a line as in read_a_line (), but insure that the prompt is
1466    the secondary prompt.  This is used to read the lines of a here
1467    document.  REMOVE_QUOTED_NEWLINE is non-zero if we should remove
1468    newlines quoted with backslashes while reading the line.  It is
1469    non-zero unless the delimiter of the here document was quoted. */
1470 char *
1471 read_secondary_line (remove_quoted_newline)
1472      int remove_quoted_newline;
1473 {
1474   prompt_string_pointer = &ps2_prompt;
1475   prompt_again ();
1476   return (read_a_line (remove_quoted_newline));
1477 }
1478
1479 /* **************************************************************** */
1480 /*                                                                  */
1481 /*                              YYLEX ()                            */
1482 /*                                                                  */
1483 /* **************************************************************** */
1484
1485 /* Reserved words.  These are only recognized as the first word of a
1486    command. */
1487 STRING_INT_ALIST word_token_alist[] = {
1488   { "if", IF },
1489   { "then", THEN },
1490   { "else", ELSE },
1491   { "elif", ELIF },
1492   { "fi", FI },
1493   { "case", CASE },
1494   { "esac", ESAC },
1495   { "for", FOR },
1496 #if defined (SELECT_COMMAND)
1497   { "select", SELECT },
1498 #endif
1499   { "while", WHILE },
1500   { "until", UNTIL },
1501   { "do", DO },
1502   { "done", DONE },
1503   { "in", IN },
1504   { "function", FUNCTION },
1505 #if defined (COMMAND_TIMING)
1506   { "time", TIME },
1507 #endif
1508   { "{", '{' },
1509   { "}", '}' },
1510   { "!", BANG },
1511 #if defined (COND_COMMAND)
1512   { "[[", COND_START },
1513   { "]]", COND_END },
1514 #endif
1515   { (char *)NULL, 0}
1516 };
1517
1518 /* XXX - we should also have an alist with strings for other tokens, so we
1519          can give more descriptive error messages.  Look at y.tab.h for the
1520          other tokens. */
1521
1522 /* These are used by read_token_word, but appear up here so that shell_getc
1523    can use them to decide when to add otherwise blank lines to the history. */
1524
1525 /* The primary delimiter stack. */
1526 struct dstack dstack = {  (char *)NULL, 0, 0 };
1527
1528 /* A temporary delimiter stack to be used when decoding prompt strings.
1529    This is needed because command substitutions in prompt strings (e.g., PS2)
1530    can screw up the parser's quoting state. */
1531 static struct dstack temp_dstack = { (char *)NULL, 0, 0 };
1532
1533 /* Macro for accessing the top delimiter on the stack.  Returns the
1534    delimiter or zero if none. */
1535 #define current_delimiter(ds) \
1536   (ds.delimiter_depth ? ds.delimiters[ds.delimiter_depth - 1] : 0)
1537
1538 #define push_delimiter(ds, character) \
1539   do \
1540     { \
1541       if (ds.delimiter_depth + 2 > ds.delimiter_space) \
1542         ds.delimiters = xrealloc \
1543           (ds.delimiters, (ds.delimiter_space += 10) * sizeof (char)); \
1544       ds.delimiters[ds.delimiter_depth] = character; \
1545       ds.delimiter_depth++; \
1546     } \
1547   while (0)
1548
1549 #define pop_delimiter(ds)       ds.delimiter_depth--
1550
1551 /* Return the next shell input character.  This always reads characters
1552    from shell_input_line; when that line is exhausted, it is time to
1553    read the next line.  This is called by read_token when the shell is
1554    processing normal command input. */
1555
1556 static int
1557 shell_getc (remove_quoted_newline)
1558      int remove_quoted_newline;
1559 {
1560   register int i;
1561   int c;
1562   static int mustpop = 0;
1563
1564   QUIT;
1565
1566 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1567   /* If shell_input_line[shell_input_line_index] == 0, but there is
1568      something on the pushed list of strings, then we don't want to go
1569      off and get another line.  We let the code down below handle it. */
1570
1571   if (!shell_input_line || ((!shell_input_line[shell_input_line_index]) &&
1572                             (pushed_string_list == (STRING_SAVER *)NULL)))
1573 #else /* !ALIAS && !DPAREN_ARITHMETIC */
1574   if (!shell_input_line || !shell_input_line[shell_input_line_index])
1575 #endif /* !ALIAS && !DPAREN_ARITHMETIC */
1576     {
1577       line_number++;
1578
1579     restart_read:
1580
1581       /* Allow immediate exit if interrupted during input. */
1582       QUIT;
1583
1584       i = 0;
1585       shell_input_line_terminator = 0;
1586
1587 #if defined (JOB_CONTROL)
1588       /* This can cause a problem when reading a command as the result
1589          of a trap, when the trap is called from flush_child.  This call
1590          had better not cause jobs to disappear from the job table in
1591          that case, or we will have big trouble. */
1592       notify_and_cleanup ();
1593 #else /* !JOB_CONTROL */
1594       cleanup_dead_jobs ();
1595 #endif /* !JOB_CONTROL */
1596
1597 #if defined (READLINE)
1598       if (interactive && bash_input.type != st_string && no_line_editing)
1599 #else
1600       if (interactive && bash_input.type != st_string)
1601 #endif
1602         print_prompt ();
1603
1604       if (bash_input.type == st_stream)
1605         clearerr (stdin);
1606
1607       while (c = yy_getc ())
1608         {
1609           /* Allow immediate exit if interrupted during input. */
1610           QUIT;
1611
1612           RESIZE_MALLOCED_BUFFER (shell_input_line, i, 2, shell_input_line_size, 256);
1613
1614           if (c == EOF)
1615             {
1616               if (bash_input.type == st_stream)
1617                 clearerr (stdin);
1618
1619               if (i == 0)
1620                 shell_input_line_terminator = EOF;
1621
1622               shell_input_line[i] = '\0';
1623               break;
1624             }
1625
1626           shell_input_line[i++] = c;
1627
1628           if (c == '\n')
1629             {
1630               shell_input_line[--i] = '\0';
1631               current_command_line_count++;
1632               break;
1633             }
1634         }
1635       shell_input_line_index = 0;
1636       shell_input_line_len = i;         /* == strlen (shell_input_line) */
1637
1638 #if defined (HISTORY)
1639       if (remember_on_history && shell_input_line && shell_input_line[0])
1640         {
1641           char *expansions;
1642 #  if defined (BANG_HISTORY)
1643           int old_hist;
1644
1645           /* If the current delimiter is a single quote, we should not be
1646              performing history expansion, even if we're on a different
1647              line from the original single quote. */
1648           old_hist = history_expansion_inhibited;
1649           if (current_delimiter (dstack) == '\'')
1650             history_expansion_inhibited = 1;
1651 #  endif
1652           expansions = pre_process_line (shell_input_line, 1, 1);
1653 #  if defined (BANG_HISTORY)
1654           history_expansion_inhibited = old_hist;
1655 #  endif
1656           if (expansions != shell_input_line)
1657             {
1658               free (shell_input_line);
1659               shell_input_line = expansions;
1660               shell_input_line_len = shell_input_line ?
1661                                         strlen (shell_input_line) : 0;
1662               if (!shell_input_line_len)
1663                 current_command_line_count--;
1664
1665               /* We have to force the xrealloc below because we don't know
1666                  the true allocated size of shell_input_line anymore. */
1667               shell_input_line_size = shell_input_line_len;
1668             }
1669         }
1670       /* XXX - this is grotesque */
1671       else if (remember_on_history && shell_input_line &&
1672                shell_input_line[0] == '\0' &&
1673                current_command_line_count > 1 && current_delimiter (dstack))
1674         {
1675           /* We know shell_input_line[0] == 0 and we're reading some sort of
1676              quoted string.  This means we've got a line consisting of only
1677              a newline in a quoted string.  We want to make sure this line
1678              gets added to the history. */
1679           maybe_add_history (shell_input_line);
1680         }
1681
1682 #endif /* HISTORY */
1683
1684       if (shell_input_line)
1685         {
1686           /* Lines that signify the end of the shell's input should not be
1687              echoed. */
1688           if (echo_input_at_read && (shell_input_line[0] ||
1689                                      shell_input_line_terminator != EOF))
1690             fprintf (stderr, "%s\n", shell_input_line);
1691         }
1692       else
1693         {
1694           shell_input_line_size = 0;
1695           prompt_string_pointer = &current_prompt_string;
1696           prompt_again ();
1697           goto restart_read;
1698         }
1699
1700       /* Add the newline to the end of this string, iff the string does
1701          not already end in an EOF character.  */
1702       if (shell_input_line_terminator != EOF)
1703         {
1704           if (shell_input_line_len + 3 > shell_input_line_size)
1705             shell_input_line = xrealloc (shell_input_line,
1706                                         1 + (shell_input_line_size += 2));
1707
1708           shell_input_line[shell_input_line_len] = '\n';
1709           shell_input_line[shell_input_line_len + 1] = '\0';
1710         }
1711     }
1712
1713   c = shell_input_line[shell_input_line_index];
1714
1715   if (c)
1716     shell_input_line_index++;
1717
1718   if (c == '\\' && remove_quoted_newline &&
1719       shell_input_line[shell_input_line_index] == '\n')
1720     {
1721         prompt_again ();
1722         line_number++;
1723         goto restart_read;
1724     }
1725
1726 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
1727   /* If C is NULL, we have reached the end of the current input string.  If
1728      pushed_string_list is non-empty, it's time to pop to the previous string
1729      because we have fully consumed the result of the last alias expansion.
1730      Do it transparently; just return the next character of the string popped
1731      to. */
1732   if (!c && (pushed_string_list != (STRING_SAVER *)NULL))
1733     {
1734       if (mustpop)
1735         {
1736           pop_string ();
1737           c = shell_input_line[shell_input_line_index];
1738           if (c)
1739             shell_input_line_index++;
1740           mustpop--;
1741         }
1742       else
1743         {
1744           mustpop++;
1745           c = ' ';
1746         }
1747     }
1748 #endif /* ALIAS || DPAREN_ARITHMETIC */
1749
1750   if (!c && shell_input_line_terminator == EOF)
1751     return ((shell_input_line_index != 0) ? '\n' : EOF);
1752
1753   return ((unsigned char)c);
1754 }
1755
1756 /* Put C back into the input for the shell. */
1757 static void
1758 shell_ungetc (c)
1759      int c;
1760 {
1761   if (shell_input_line && shell_input_line_index)
1762     shell_input_line[--shell_input_line_index] = c;
1763 }
1764
1765 static void
1766 shell_ungetchar ()
1767 {
1768   if (shell_input_line && shell_input_line_index)
1769     shell_input_line_index--;
1770 }
1771
1772 /* Discard input until CHARACTER is seen, then push that character back
1773    onto the input stream. */
1774 static void
1775 discard_until (character)
1776      int character;
1777 {
1778   int c;
1779
1780   while ((c = shell_getc (0)) != EOF && c != character)
1781     ;
1782
1783   if (c != EOF)
1784     shell_ungetc (c);
1785 }
1786
1787 void
1788 execute_prompt_command (command)
1789      char *command;
1790 {
1791   Function *temp_last, *temp_this;
1792   char *last_lastarg;
1793   int temp_exit_value, temp_eof_encountered;
1794
1795   temp_last = last_shell_builtin;
1796   temp_this = this_shell_builtin;
1797   temp_exit_value = last_command_exit_value;
1798   temp_eof_encountered = eof_encountered;
1799   last_lastarg = get_string_value ("_");
1800   if (last_lastarg)
1801     last_lastarg = savestring (last_lastarg);
1802
1803   parse_and_execute (savestring (command), "PROMPT_COMMAND", SEVAL_NONINT|SEVAL_NOHIST);
1804
1805   last_shell_builtin = temp_last;
1806   this_shell_builtin = temp_this;
1807   last_command_exit_value = temp_exit_value;
1808   eof_encountered = temp_eof_encountered;
1809
1810   bind_variable ("_", last_lastarg);
1811   FREE (last_lastarg);
1812
1813   if (token_to_read == '\n')    /* reset_parser was called */
1814     token_to_read = 0;
1815 }
1816
1817 /* Place to remember the token.  We try to keep the buffer
1818    at a reasonable size, but it can grow. */
1819 static char *token = (char *)NULL;
1820
1821 /* Current size of the token buffer. */
1822 static int token_buffer_size;
1823
1824 /* Command to read_token () explaining what we want it to do. */
1825 #define READ 0
1826 #define RESET 1
1827 #define prompt_is_ps1 \
1828       (!prompt_string_pointer || prompt_string_pointer == &ps1_prompt)
1829
1830 /* Function for yyparse to call.  yylex keeps track of
1831    the last two tokens read, and calls read_token.  */
1832 static int
1833 yylex ()
1834 {
1835   if (interactive && (current_token == 0 || current_token == '\n'))
1836     {
1837       /* Before we print a prompt, we might have to check mailboxes.
1838          We do this only if it is time to do so. Notice that only here
1839          is the mail alarm reset; nothing takes place in check_mail ()
1840          except the checking of mail.  Please don't change this. */
1841       if (prompt_is_ps1 && time_to_check_mail ())
1842         {
1843           check_mail ();
1844           reset_mail_timer ();
1845         }
1846
1847       /* Avoid printing a prompt if we're not going to read anything, e.g.
1848          after resetting the parser with read_token (RESET). */
1849       if (token_to_read == 0 && interactive)
1850         prompt_again ();
1851     }
1852
1853   two_tokens_ago = token_before_that;
1854   token_before_that = last_read_token;
1855   last_read_token = current_token;
1856   current_token = read_token (READ);
1857   return (current_token);
1858 }
1859
1860 /* When non-zero, we have read the required tokens
1861    which allow ESAC to be the next one read. */
1862 static int esacs_needed_count;
1863
1864 void
1865 gather_here_documents ()
1866 {
1867   int r = 0;
1868   while (need_here_doc)
1869     {
1870       make_here_document (redir_stack[r++]);
1871       need_here_doc--;
1872     }
1873 }
1874
1875 /* When non-zero, an open-brace used to create a group is awaiting a close
1876    brace partner. */
1877 static int open_brace_count;
1878
1879 #define command_token_position(token) \
1880   (((token) == ASSIGNMENT_WORD) || \
1881    ((token) != SEMI_SEMI && reserved_word_acceptable(token)))
1882
1883 #define assignment_acceptable(token) command_token_position(token) && \
1884                                         ((parser_state & PST_CASEPAT) == 0)
1885
1886 /* Check to see if TOKEN is a reserved word and return the token
1887    value if it is. */
1888 #define CHECK_FOR_RESERVED_WORD(tok) \
1889   do { \
1890     if (!dollar_present && !quoted && \
1891         reserved_word_acceptable (last_read_token)) \
1892       { \
1893         int i; \
1894         for (i = 0; word_token_alist[i].word != (char *)NULL; i++) \
1895           if (STREQ (tok, word_token_alist[i].word)) \
1896             { \
1897               if ((parser_state & PST_CASEPAT) && (word_token_alist[i].token != ESAC)) \
1898                 break; \
1899               if (word_token_alist[i].token == TIME) \
1900                 break; \
1901               if (word_token_alist[i].token == ESAC) \
1902                 parser_state &= ~(PST_CASEPAT|PST_CASESTMT); \
1903               else if (word_token_alist[i].token == CASE) \
1904                 parser_state |= PST_CASESTMT; \
1905               else if (word_token_alist[i].token == COND_END) \
1906                 parser_state &= ~(PST_CONDCMD|PST_CONDEXPR); \
1907               else if (word_token_alist[i].token == COND_START) \
1908                 parser_state |= PST_CONDCMD; \
1909               else if (word_token_alist[i].token == '{') \
1910                 open_brace_count++; \
1911               else if (word_token_alist[i].token == '}' && open_brace_count) \
1912                 open_brace_count--; \
1913               return (word_token_alist[i].token); \
1914             } \
1915       } \
1916   } while (0)
1917
1918 #if defined (ALIAS)
1919
1920     /* OK, we have a token.  Let's try to alias expand it, if (and only if)
1921        it's eligible.
1922
1923        It is eligible for expansion if the shell is in interactive mode, and
1924        the token is unquoted and the last token read was a command
1925        separator (or expand_next_token is set), and we are currently
1926        processing an alias (pushed_string_list is non-empty) and this
1927        token is not the same as the current or any previously
1928        processed alias.
1929
1930        Special cases that disqualify:
1931          In a pattern list in a case statement (parser_state & PST_CASEPAT). */
1932 static int
1933 alias_expand_token (token)
1934      char *token;
1935 {
1936   char *expanded;
1937   alias_t *ap;
1938
1939   if (((parser_state & PST_ALEXPNEXT) || command_token_position (last_read_token)) &&
1940         (parser_state & PST_CASEPAT) == 0)
1941     {
1942       ap = find_alias (token);
1943
1944       /* Currently expanding this token. */
1945       if (ap && (ap->flags & AL_BEINGEXPANDED))
1946         return (NO_EXPANSION);
1947
1948       expanded = ap ? savestring (ap->value) : (char *)NULL;
1949       if (expanded)
1950         {
1951           push_string (expanded, ap->flags & AL_EXPANDNEXT, ap);
1952           return (RE_READ_TOKEN);
1953         }
1954       else
1955         /* This is an eligible token that does not have an expansion. */
1956         return (NO_EXPANSION);
1957     }
1958   return (NO_EXPANSION);
1959 }
1960 #endif /* ALIAS */
1961
1962 static int
1963 time_command_acceptable ()
1964 {
1965 #if defined (COMMAND_TIMING)
1966   switch (last_read_token)
1967     {
1968     case 0:
1969     case ';':
1970     case '\n':
1971     case AND_AND:
1972     case OR_OR:
1973     case '&':
1974     case DO:
1975     case THEN:
1976     case ELSE:
1977     case '{':
1978     case '(':
1979       return 1;
1980     default:
1981       return 0;
1982     }
1983 #else
1984   return 0;
1985 #endif /* COMMAND_TIMING */
1986 }
1987
1988 /* Handle special cases of token recognition:
1989         IN is recognized if the last token was WORD and the token
1990         before that was FOR or CASE or SELECT.
1991
1992         DO is recognized if the last token was WORD and the token
1993         before that was FOR or SELECT.
1994
1995         ESAC is recognized if the last token caused `esacs_needed_count'
1996         to be set
1997
1998         `{' is recognized if the last token as WORD and the token
1999         before that was FUNCTION.
2000
2001         `}' is recognized if there is an unclosed `{' prsent.
2002
2003         `-p' is returned as TIMEOPT if the last read token was TIME.
2004
2005         ']]' is returned as COND_END if the parser is currently parsing
2006         a conditional expression ((parser_state & PST_CONDEXPR) != 0)
2007
2008         `time' is returned as TIME if and only if it is immediately
2009         preceded by one of `;', `\n', `||', `&&', or `&'.
2010 */
2011
2012 static int
2013 special_case_tokens (token)
2014      char *token;
2015 {
2016   if ((last_read_token == WORD) &&
2017 #if defined (SELECT_COMMAND)
2018       ((token_before_that == FOR) || (token_before_that == CASE) || (token_before_that == SELECT)) &&
2019 #else
2020       ((token_before_that == FOR) || (token_before_that == CASE)) &&
2021 #endif
2022       (token[0] == 'i' && token[1] == 'n' && token[2] == 0))
2023     {
2024       if (token_before_that == CASE)
2025         {
2026           parser_state |= PST_CASEPAT;
2027           esacs_needed_count++;
2028         }
2029       return (IN);
2030     }
2031
2032   if (last_read_token == WORD &&
2033 #if defined (SELECT_COMMAND)
2034       (token_before_that == FOR || token_before_that == SELECT) &&
2035 #else
2036       (token_before_that == FOR) &&
2037 #endif
2038       (token[0] == 'd' && token[1] == 'o' && token[2] == '\0'))
2039     return (DO);
2040
2041   /* Ditto for ESAC in the CASE case.
2042      Specifically, this handles "case word in esac", which is a legal
2043      construct, certainly because someone will pass an empty arg to the
2044      case construct, and we don't want it to barf.  Of course, we should
2045      insist that the case construct has at least one pattern in it, but
2046      the designers disagree. */
2047   if (esacs_needed_count)
2048     {
2049       esacs_needed_count--;
2050       if (STREQ (token, "esac"))
2051         {
2052           parser_state &= ~PST_CASEPAT;
2053           return (ESAC);
2054         }
2055     }
2056
2057   /* The start of a shell function definition. */
2058   if (parser_state & PST_ALLOWOPNBRC)
2059     {
2060       parser_state &= ~PST_ALLOWOPNBRC;
2061       if (token[0] == '{' && token[1] == '\0')          /* } */
2062         {
2063           open_brace_count++;
2064           function_bstart = line_number;
2065           return ('{');                                 /* } */
2066         }
2067     }
2068
2069   if (open_brace_count && reserved_word_acceptable (last_read_token) && token[0] == '}' && !token[1])
2070     {
2071       open_brace_count--;               /* { */
2072       return ('}');
2073     }
2074
2075 #if defined (COMMAND_TIMING)
2076   /* Handle -p after `time'. */
2077   if (last_read_token == TIME && token[0] == '-' && token[1] == 'p' && !token[2])
2078     return (TIMEOPT);
2079 #endif
2080
2081 #if defined (COMMAND_TIMING)
2082   if (STREQ (token, "time") && ((parser_state & PST_CASEPAT) == 0) && time_command_acceptable ())
2083     return (TIME);
2084 #endif /* COMMAND_TIMING */
2085
2086 #if defined (COND_COMMAND) /* [[ */
2087   if ((parser_state & PST_CONDEXPR) && token[0] == ']' && token[1] == ']' && token[2] == '\0')
2088     return (COND_END);
2089 #endif
2090
2091   return (-1);
2092 }
2093
2094 /* Called from shell.c when Control-C is typed at top level.  Or
2095    by the error rule at top level. */
2096 void
2097 reset_parser ()
2098 {
2099   dstack.delimiter_depth = 0;   /* No delimiters found so far. */
2100   open_brace_count = 0;
2101
2102   parser_state = 0;
2103
2104 #if defined (ALIAS) || defined (DPAREN_ARITHMETIC)
2105   if (pushed_string_list)
2106     free_string_list ();
2107 #endif /* ALIAS || DPAREN_ARITHMETIC */
2108
2109   if (shell_input_line)
2110     {
2111       free (shell_input_line);
2112       shell_input_line = (char *)NULL;
2113       shell_input_line_size = shell_input_line_index = 0;
2114     }
2115
2116   FREE (word_desc_to_read);
2117   word_desc_to_read = (WORD_DESC *)NULL;
2118
2119   last_read_token = '\n';
2120   token_to_read = '\n';
2121 }
2122
2123 /* Read the next token.  Command can be READ (normal operation) or
2124    RESET (to normalize state). */
2125 static int
2126 read_token (command)
2127      int command;
2128 {
2129   int character;                /* Current character. */
2130   int peek_char;                /* Temporary look-ahead character. */
2131   int result;                   /* The thing to return. */
2132
2133   if (command == RESET)
2134     {
2135       reset_parser ();
2136       return ('\n');
2137     }
2138
2139   if (token_to_read)
2140     {
2141       result = token_to_read;
2142       if (token_to_read == WORD || token_to_read == ASSIGNMENT_WORD)
2143         {
2144           yylval.word = word_desc_to_read;
2145           word_desc_to_read = (WORD_DESC *)NULL;
2146         }
2147       token_to_read = 0;
2148       return (result);
2149     }
2150
2151 #if defined (COND_COMMAND)
2152   if ((parser_state & (PST_CONDCMD|PST_CONDEXPR)) == PST_CONDCMD)
2153     {
2154       cond_lineno = line_number;
2155       parser_state |= PST_CONDEXPR;
2156       yylval.command = parse_cond_command ();
2157       if (cond_token != COND_END)
2158         {
2159           if (EOF_Reached && cond_token != COND_ERROR)          /* [[ */
2160             parser_error (cond_lineno, "unexpected EOF while looking for `]]'");
2161           else if (cond_token != COND_ERROR)
2162             parser_error (cond_lineno, "syntax error in conditional expression");
2163           return (-1);
2164         }
2165       token_to_read = COND_END;
2166       parser_state &= ~(PST_CONDEXPR|PST_CONDCMD);
2167       return (COND_CMD);
2168     }
2169 #endif
2170
2171 #if defined (ALIAS)
2172   /* This is a place to jump back to once we have successfully expanded a
2173      token with an alias and pushed the string with push_string () */
2174  re_read_token:
2175 #endif /* ALIAS */
2176
2177   /* Read a single word from input.  Start by skipping blanks. */
2178   while ((character = shell_getc (1)) != EOF && whitespace (character))
2179     ;
2180
2181   if (character == EOF)
2182     {
2183       EOF_Reached = 1;
2184       return (yacc_EOF);
2185     }
2186
2187   if (character == '#' && (!interactive || interactive_comments))
2188     {
2189       /* A comment.  Discard until EOL or EOF, and then return a newline. */
2190       discard_until ('\n');
2191       shell_getc (0);
2192       character = '\n'; /* this will take the next if statement and return. */
2193     }
2194
2195   if (character == '\n')
2196     {
2197       /* If we're about to return an unquoted newline, we can go and collect
2198          the text of any pending here document. */
2199       if (need_here_doc)
2200         gather_here_documents ();
2201
2202 #if defined (ALIAS)
2203       parser_state &= ~PST_ALEXPNEXT;
2204 #endif /* ALIAS */
2205
2206       return (character);
2207     }
2208
2209   /* Shell meta-characters. */
2210   if (shellmeta (character) && ((parser_state & PST_DBLPAREN) == 0))
2211     {
2212 #if defined (ALIAS)
2213       /* Turn off alias tokenization iff this character sequence would
2214          not leave us ready to read a command. */
2215       if (character == '<' || character == '>')
2216         parser_state &= ~PST_ALEXPNEXT;
2217 #endif /* ALIAS */
2218
2219       peek_char = shell_getc (1);
2220       if (character == peek_char)
2221         {
2222           switch (character)
2223             {
2224             case '<':
2225               /* If '<' then we could be at "<<" or at "<<-".  We have to
2226                  look ahead one more character. */
2227               peek_char = shell_getc (1);
2228               if (peek_char == '-')
2229                 return (LESS_LESS_MINUS);
2230               else
2231                 {
2232                   shell_ungetc (peek_char);
2233                   return (LESS_LESS);
2234                 }
2235
2236             case '>':
2237               return (GREATER_GREATER);
2238
2239             case ';':
2240               parser_state |= PST_CASEPAT;
2241 #if defined (ALIAS)
2242               parser_state &= ~PST_ALEXPNEXT;
2243 #endif /* ALIAS */
2244               return (SEMI_SEMI);
2245
2246             case '&':
2247               return (AND_AND);
2248
2249             case '|':
2250               return (OR_OR);
2251
2252 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2253             case '(':           /* ) */
2254 #  if defined (ARITH_FOR_COMMAND)
2255               if (last_read_token == FOR)
2256                 {
2257                   int cmdtyp, len;
2258                   char *wval, *wv2;
2259                   WORD_DESC *wd;
2260
2261                   arith_for_lineno = line_number;
2262                   cmdtyp = parse_arith_cmd (&wval);
2263                   if (cmdtyp == 1)
2264                     {
2265                       /* parse_arith_cmd adds quotes at the beginning and end
2266                          of the string it returns; we need to take those out. */
2267                       len = strlen (wval);
2268                       wv2 = xmalloc (len);
2269                       strncpy (wv2, wval + 1, len - 2);
2270                       wv2[len - 2] = '\0';
2271                       wd = make_word (wv2);
2272                       yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2273                       free (wval);
2274                       free (wv2);
2275                       return (ARITH_FOR_EXPRS);
2276                     }
2277                   else
2278                     return -1;          /* ERROR */
2279                 }
2280 #  endif
2281 #  if defined (DPAREN_ARITHMETIC)
2282               if (reserved_word_acceptable (last_read_token))
2283                 {
2284                   int cmdtyp, sline;
2285                   char *wval;
2286                   WORD_DESC *wd;
2287
2288                   sline = line_number;
2289                   cmdtyp = parse_arith_cmd (&wval);
2290                   if (cmdtyp == 1)      /* arithmetic command */
2291                     {
2292                       wd = make_word (wval);
2293                       wd->flags = W_QUOTED;
2294                       yylval.word_list = make_word_list (wd, (WORD_LIST *)NULL);
2295                       free (wval);      /* make_word copies it */
2296                       return (ARITH_CMD);
2297                     }
2298                   else if (cmdtyp == 0) /* nested subshell */
2299                     {
2300                       push_string (wval, 0, (alias_t *)NULL);
2301                       if ((parser_state & PST_CASEPAT) == 0)
2302                         parser_state |= PST_SUBSHELL;
2303                       return (character);
2304                     }
2305                   else                  /* ERROR */
2306                     return -1;
2307                 }
2308               break;
2309 #  endif
2310 #endif
2311             }
2312         }
2313       else if (character == '<' && peek_char == '&')
2314         return (LESS_AND);
2315       else if (character == '>' && peek_char == '&')
2316         return (GREATER_AND);
2317       else if (character == '<' && peek_char == '>')
2318         return (LESS_GREATER);
2319       else if (character == '>' && peek_char == '|')
2320         return (GREATER_BAR);
2321       else if (peek_char == '>' && character == '&')
2322         return (AND_GREATER);
2323
2324       shell_ungetc (peek_char);
2325
2326       /* If we look like we are reading the start of a function
2327          definition, then let the reader know about it so that
2328          we will do the right thing with `{'. */
2329       if (character == ')' && last_read_token == '(' && token_before_that == WORD)
2330         {
2331           parser_state |= PST_ALLOWOPNBRC;
2332 #if defined (ALIAS)
2333           parser_state &= ~PST_ALEXPNEXT;
2334 #endif /* ALIAS */
2335           function_dstart = line_number;
2336         }
2337
2338       /* case pattern lists may be preceded by an optional left paren.  If
2339          we're not trying to parse a case pattern list, the left paren
2340          indicates a subshell. */
2341       if (character == '(' && (parser_state & PST_CASEPAT) == 0) /* ) */
2342         parser_state |= PST_SUBSHELL;
2343       /*(*/
2344       else if ((parser_state & PST_CASEPAT) && character == ')')
2345         parser_state &= ~PST_CASEPAT;
2346       /*(*/
2347       else if ((parser_state & PST_SUBSHELL) && character == ')')
2348         parser_state &= ~PST_SUBSHELL;
2349
2350 #if defined (PROCESS_SUBSTITUTION)
2351       /* Check for the constructs which introduce process substitution.
2352          Shells running in `posix mode' don't do process substitution. */
2353       if (posixly_correct ||
2354           ((character != '>' && character != '<') || peek_char != '('))
2355 #endif /* PROCESS_SUBSTITUTION */
2356         return (character);
2357     }
2358
2359   /* Hack <&- (close stdin) case. */
2360   if (character == '-' && (last_read_token == LESS_AND || last_read_token == GREATER_AND))
2361     return (character);
2362
2363   /* Okay, if we got this far, we have to read a word.  Read one,
2364      and then check it against the known ones. */
2365   result = read_token_word (character);
2366 #if defined (ALIAS)
2367   if (result == RE_READ_TOKEN)
2368     goto re_read_token;
2369 #endif
2370   return result;
2371 }
2372
2373 /* Match a $(...) or other grouping construct.  This has to handle embedded
2374    quoted strings ('', ``, "") and nested constructs.  It also must handle
2375    reprompting the user, if necessary, after reading a newline, and returning
2376    correct error values if it reads EOF. */
2377
2378 #define P_FIRSTCLOSE    0x01
2379 #define P_ALLOWESC      0x02
2380
2381 static char matched_pair_error;
2382 static char *
2383 parse_matched_pair (qc, open, close, lenp, flags)
2384      int qc;    /* `"' if this construct is within double quotes */
2385      int open, close;
2386      int *lenp, flags;
2387 {
2388   int count, ch, was_dollar;
2389   int pass_next_character, nestlen, start_lineno;
2390   char *ret, *nestret;
2391   int retind, retsize;
2392
2393   count = 1;
2394   pass_next_character = was_dollar = 0;
2395
2396   ret = xmalloc (retsize = 64);
2397   retind = 0;
2398
2399   start_lineno = line_number;
2400   while (count)
2401     {
2402       ch = shell_getc ((qc != '\'' || (flags & P_ALLOWESC)) && pass_next_character == 0);
2403       if (ch == EOF)
2404         {
2405           free (ret);
2406           parser_error (start_lineno, "unexpected EOF while looking for matching `%c'", close);
2407           EOF_Reached = 1;      /* XXX */
2408           return (&matched_pair_error);
2409         }
2410
2411       /* Possible reprompting. */
2412       if (ch == '\n' && interactive &&
2413             (bash_input.type == st_stdin || bash_input.type == st_stream))
2414         prompt_again ();
2415
2416       if (pass_next_character)          /* last char was backslash */
2417         {
2418           pass_next_character = 0;
2419           if (qc != '\'' && ch == '\n') /* double-quoted \<newline> disappears. */
2420             {
2421               if (retind > 0) retind--; /* swallow previously-added backslash */
2422               continue;
2423             }
2424
2425           RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2426           if (ch == CTLESC || ch == CTLNUL)
2427             ret[retind++] = CTLESC;
2428           ret[retind++] = ch;
2429           continue;
2430         }
2431       else if (ch == CTLESC || ch == CTLNUL)    /* special shell escapes */
2432         {
2433           RESIZE_MALLOCED_BUFFER (ret, retind, 2, retsize, 64);
2434           ret[retind++] = CTLESC;
2435           ret[retind++] = ch;
2436           continue;
2437         }
2438       else if (ch == close)             /* ending delimiter */
2439         count--;
2440 #if 1
2441       /* handle nested ${...} specially. */
2442       else if (open != close && was_dollar && open == '{' && ch == open) /* } */
2443         count++;
2444 #endif
2445       else if (((flags & P_FIRSTCLOSE) == 0) && ch == open)             /* nested begin */
2446         count++;
2447
2448       /* Add this character. */
2449       RESIZE_MALLOCED_BUFFER (ret, retind, 1, retsize, 64);
2450       ret[retind++] = ch;
2451
2452       if (open == '\'')                 /* '' inside grouping construct */
2453         {
2454           if ((flags & P_ALLOWESC) && ch == '\\')
2455             pass_next_character++;
2456           continue;
2457         }
2458
2459       if (ch == '\\')                   /* backslashes */
2460         pass_next_character++;
2461
2462       if (open != close)                /* a grouping construct */
2463         {
2464           if (shellquote (ch))
2465             {
2466               /* '', ``, or "" inside $(...) or other grouping construct. */
2467               push_delimiter (dstack, ch);
2468               nestret = parse_matched_pair (ch, ch, ch, &nestlen, 0);
2469               pop_delimiter (dstack);
2470               if (nestret == &matched_pair_error)
2471                 {
2472                   free (ret);
2473                   return &matched_pair_error;
2474                 }
2475               if (nestlen)
2476                 {
2477                   RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2478                   strcpy (ret + retind, nestret);
2479                   retind += nestlen;
2480                 }
2481               FREE (nestret);
2482             }
2483         }
2484       /* Parse an old-style command substitution within double quotes as a
2485          single word. */
2486       /* XXX - sh and ksh93 don't do this - XXX */
2487       else if (open == '"' && ch == '`')
2488         {
2489           nestret = parse_matched_pair (0, '`', '`', &nestlen, 0);
2490           if (nestret == &matched_pair_error)
2491             {
2492               free (ret);
2493               return &matched_pair_error;
2494             }
2495           if (nestlen)
2496             {
2497               RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2498               strcpy (ret + retind, nestret);
2499               retind += nestlen;
2500             }
2501           FREE (nestret);
2502         }
2503       else if (was_dollar && (ch == '(' || ch == '{' || ch == '['))     /* ) } ] */
2504         /* check for $(), $[], or ${} inside quoted string. */
2505         {
2506           if (open == ch)       /* undo previous increment */
2507             count--;
2508           if (ch == '(')                /* ) */
2509             nestret = parse_matched_pair (0, '(', ')', &nestlen, 0);
2510           else if (ch == '{')           /* } */
2511             nestret = parse_matched_pair (0, '{', '}', &nestlen, P_FIRSTCLOSE);
2512           else if (ch == '[')           /* ] */
2513             nestret = parse_matched_pair (0, '[', ']', &nestlen, 0);
2514           if (nestret == &matched_pair_error)
2515             {
2516               free (ret);
2517               return &matched_pair_error;
2518             }
2519           if (nestlen)
2520             {
2521               RESIZE_MALLOCED_BUFFER (ret, retind, nestlen, retsize, 64);
2522               strcpy (ret + retind, nestret);
2523               retind += nestlen;
2524             }
2525           FREE (nestret);
2526         }
2527       was_dollar = (ch == '$');
2528     }
2529
2530   ret[retind] = '\0';
2531   if (lenp)
2532     *lenp = retind;
2533   return ret;
2534 }
2535
2536 #if defined (DPAREN_ARITHMETIC) || defined (ARITH_FOR_COMMAND)
2537 /* We've seen a `(('.  Look for the matching `))'.  If we get it, return 1.
2538    If not, assume it's a nested subshell for backwards compatibility and
2539    return 0.  In any case, put the characters we've consumed into a locally-
2540    allocated buffer and make *ep point to that buffer.  Return -1 on an
2541    error, for example EOF. */
2542 static int
2543 parse_arith_cmd (ep)
2544      char **ep;
2545 {
2546   int exp_lineno, rval, c;
2547   char *ttok, *token;
2548   int ttoklen;
2549
2550   exp_lineno = line_number;
2551   ttok = parse_matched_pair (0, '(', ')', &ttoklen, 0);
2552   rval = 1;
2553   if (ttok == &matched_pair_error)
2554     return -1;
2555   /* Check that the next character is the closing right paren.  If
2556      not, this is a syntax error. ( */
2557   if ((c = shell_getc (0)) != ')')
2558     rval = 0;
2559
2560   token = xmalloc (ttoklen + 4);
2561
2562   /* (( ... )) -> "..." */
2563   token[0] = (rval == 1) ? '"' : '(';
2564   strncpy (token + 1, ttok, ttoklen - 1);       /* don't copy the final `)' */
2565   if (rval == 1)
2566     {
2567       token[ttoklen] = '"';
2568       token[ttoklen+1] = '\0';
2569     }
2570   else
2571     {
2572       token[ttoklen] = ')';
2573       token[ttoklen+1] = c;
2574       token[ttoklen+2] = '\0';
2575     }
2576   *ep = token;
2577   FREE (ttok);
2578   return rval;
2579 }
2580 #endif /* DPAREN_ARITHMETIC || ARITH_FOR_COMMAND */
2581
2582 #if defined (COND_COMMAND)
2583 static COND_COM *cond_term ();
2584 static COND_COM *cond_and ();
2585 static COND_COM *cond_or ();
2586 static COND_COM *cond_expr ();
2587
2588 static COND_COM *
2589 cond_expr ()
2590 {
2591   return (cond_or ());  
2592 }
2593
2594 static COND_COM *
2595 cond_or ()
2596 {
2597   COND_COM *l, *r;
2598
2599   l = cond_and ();
2600   if (cond_token == OR_OR)
2601     {
2602       r = cond_or ();
2603       l = make_cond_node (COND_OR, (WORD_DESC *)NULL, l, r);
2604     }
2605   return l;
2606 }
2607
2608 static COND_COM *
2609 cond_and ()
2610 {
2611   COND_COM *l, *r;
2612
2613   l = cond_term ();
2614   if (cond_token == AND_AND)
2615     {
2616       r = cond_and ();
2617       l = make_cond_node (COND_AND, (WORD_DESC *)NULL, l, r);
2618     }
2619   return l;
2620 }
2621
2622 static int
2623 cond_skip_newlines ()
2624 {
2625   while ((cond_token = read_token (READ)) == '\n')
2626     {
2627       if (interactive && (bash_input.type == st_stdin || bash_input.type == st_stream))
2628         prompt_again ();
2629     }
2630   return (cond_token);
2631 }
2632
2633 #define COND_RETURN_ERROR() \
2634   do { cond_token = COND_ERROR; return ((COND_COM *)NULL); } while (0)
2635
2636 static COND_COM *
2637 cond_term ()
2638 {
2639   WORD_DESC *op;
2640   COND_COM *term, *tleft, *tright;
2641   int tok, lineno;
2642
2643   /* Read a token.  It can be a left paren, a `!', a unary operator, or a
2644      word that should be the first argument of a binary operator.  Start by
2645      skipping newlines, since this is a compound command. */
2646   tok = cond_skip_newlines ();
2647   lineno = line_number;
2648   if (tok == COND_END)
2649     {
2650       COND_RETURN_ERROR ();
2651     }
2652   else if (tok == '(')
2653     {
2654       term = cond_expr ();
2655       if (cond_token != ')')
2656         {
2657           if (term)
2658             dispose_cond_node (term);           /* ( */
2659           parser_error (lineno, "expected `)'");
2660           COND_RETURN_ERROR ();
2661         }
2662       term = make_cond_node (COND_EXPR, (WORD_DESC *)NULL, term, (COND_COM *)NULL);
2663       (void)cond_skip_newlines ();
2664     }
2665   else if (tok == BANG || (tok == WORD && (yylval.word->word[0] == '!' && yylval.word->word[1] == '\0')))
2666     {
2667       if (tok == WORD)
2668         dispose_word (yylval.word);     /* not needed */
2669       term = cond_term ();
2670       if (term)
2671         term->flags |= CMD_INVERT_RETURN;
2672     }
2673   else if (tok == WORD && test_unop (yylval.word->word))
2674     {
2675       op = yylval.word;
2676       tok = read_token (READ);
2677       if (tok == WORD)
2678         {
2679           tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
2680           term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
2681         }
2682       else
2683         {
2684           dispose_word (op);
2685           parser_error (line_number, "unexpected argument to conditional unary operator");
2686           COND_RETURN_ERROR ();
2687         }
2688
2689       (void)cond_skip_newlines ();
2690     }
2691   else if (tok == WORD)         /* left argument to binary operator */
2692     {
2693       /* lhs */
2694       tleft = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
2695
2696       /* binop */
2697       tok = read_token (READ);
2698       if (tok == WORD && test_binop (yylval.word->word))
2699         op = yylval.word;
2700       else if (tok == '<' || tok == '>')
2701         op = make_word_from_token (tok);
2702       else if (tok == COND_END || tok == AND_AND || tok == OR_OR)
2703         {
2704           /* Special case.  [[ x ]] is equivalent to [[ -n x ]], just like
2705              the test command.  Similarly for [[ x && expr ]] or
2706              [[ x || expr ]] */
2707           op = make_word ("-n");
2708           term = make_cond_node (COND_UNARY, op, tleft, (COND_COM *)NULL);
2709           cond_token = tok;
2710           return (term);
2711         }
2712       else
2713         {
2714           parser_error (line_number, "conditional binary operator expected");
2715           dispose_cond_node (tleft);
2716           COND_RETURN_ERROR ();
2717         }
2718
2719       /* rhs */
2720       tok = read_token (READ);
2721       if (tok == WORD)
2722         {
2723           tright = make_cond_node (COND_TERM, yylval.word, (COND_COM *)NULL, (COND_COM *)NULL);
2724           term = make_cond_node (COND_BINARY, op, tleft, tright);
2725         }
2726       else
2727         {
2728           parser_error (line_number, "unexpected argument to conditional binary operator");
2729           dispose_cond_node (tleft);
2730           dispose_word (op);
2731           COND_RETURN_ERROR ();
2732         }
2733
2734       (void)cond_skip_newlines ();
2735     }
2736   else
2737     {
2738       if (tok < 256)
2739         parser_error (line_number, "unexpected token `%c' in conditional command", tok);
2740       else
2741         parser_error (line_number, "unexpected token %d in conditional command", tok);
2742       COND_RETURN_ERROR ();
2743     }
2744   return (term);
2745 }      
2746
2747 /* This is kind of bogus -- we slip a mini recursive-descent parser in
2748    here to handle the conditional statement syntax. */
2749 static COMMAND *
2750 parse_cond_command ()
2751 {
2752   COND_COM *cexp;
2753
2754   cexp = cond_expr ();
2755   return (make_cond_command (cexp));
2756 }
2757 #endif
2758
2759 static int
2760 read_token_word (character)
2761      int character;
2762 {
2763   /* The value for YYLVAL when a WORD is read. */
2764   WORD_DESC *the_word;
2765
2766   /* Index into the token that we are building. */
2767   int token_index;
2768
2769   /* ALL_DIGITS becomes zero when we see a non-digit. */
2770   int all_digits;
2771
2772   /* DOLLAR_PRESENT becomes non-zero if we see a `$'. */
2773   int dollar_present;
2774
2775   /* QUOTED becomes non-zero if we see one of ("), ('), (`), or (\). */
2776   int quoted;
2777
2778   /* Non-zero means to ignore the value of the next character, and just
2779      to add it no matter what. */
2780  int pass_next_character;
2781
2782   /* The current delimiting character. */
2783   int cd;
2784   int result, peek_char;
2785   char *ttok, *ttrans;
2786   int ttoklen, ttranslen;
2787
2788   if (token_buffer_size < TOKEN_DEFAULT_INITIAL_SIZE)
2789     token = xrealloc (token, token_buffer_size = TOKEN_DEFAULT_INITIAL_SIZE);
2790
2791   token_index = 0;
2792   all_digits = digit (character);
2793   dollar_present = quoted = pass_next_character = 0;
2794
2795   for (;;)
2796     {
2797       if (character == EOF)
2798         goto got_token;
2799
2800       if (pass_next_character)
2801         {
2802           pass_next_character = 0;
2803           goto got_character;
2804         }
2805
2806       cd = current_delimiter (dstack);
2807
2808       /* Handle backslashes.  Quote lots of things when not inside of
2809          double-quotes, quote some things inside of double-quotes. */
2810       if (character == '\\')
2811         {
2812           peek_char = shell_getc (0);
2813
2814           /* Backslash-newline is ignored in all cases except
2815              when quoted with single quotes. */
2816           if (peek_char == '\n')
2817             {
2818               character = '\n';
2819               goto next_character;
2820             }
2821           else
2822             {
2823               shell_ungetc (peek_char);
2824
2825               /* If the next character is to be quoted, note it now. */
2826               if (cd == 0 || cd == '`' ||
2827                   (cd == '"' && member (peek_char, slashify_in_quotes)))
2828                 pass_next_character++;
2829
2830               quoted = 1;
2831               goto got_character;
2832             }
2833         }
2834
2835       /* Parse a matched pair of quote characters. */
2836       if (shellquote (character))
2837         {
2838           push_delimiter (dstack, character);
2839           ttok = parse_matched_pair (character, character, character, &ttoklen, 0);
2840           pop_delimiter (dstack);
2841           if (ttok == &matched_pair_error)
2842             return -1;          /* Bail immediately. */
2843           RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2844                                   token_buffer_size, TOKEN_DEFAULT_GROW_SIZE);
2845           token[token_index++] = character;
2846           strcpy (token + token_index, ttok);
2847           token_index += ttoklen;
2848           all_digits = 0;
2849           quoted = 1;
2850           dollar_present |= (character == '"' && strchr (ttok, '$') != 0);
2851           FREE (ttok);
2852           goto next_character;
2853         }
2854
2855 #ifdef EXTENDED_GLOB
2856       /* Parse a ksh-style extended pattern matching specification. */
2857       if (extended_glob && PATTERN_CHAR(character))
2858         {
2859           peek_char = shell_getc (1);
2860           if (peek_char == '(')         /* ) */
2861             {
2862               push_delimiter (dstack, peek_char);
2863               ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
2864               pop_delimiter (dstack);
2865               if (ttok == &matched_pair_error)
2866                 return -1;              /* Bail immediately. */
2867               RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2868                                       token_buffer_size,
2869                                       TOKEN_DEFAULT_GROW_SIZE);
2870               token[token_index++] = character;
2871               token[token_index++] = peek_char;
2872               strcpy (token + token_index, ttok);
2873               token_index += ttoklen;
2874               FREE (ttok);
2875               dollar_present = all_digits = 0;
2876               goto next_character;
2877             }
2878           else
2879             shell_ungetc (peek_char);
2880         }
2881 #endif /* EXTENDED_GLOB */
2882
2883       /* If the delimiter character is not single quote, parse some of
2884          the shell expansions that must be read as a single word. */
2885 #if defined (PROCESS_SUBSTITUTION)
2886       if (character == '$' || character == '<' || character == '>')
2887 #else
2888       if (character == '$')
2889 #endif /* !PROCESS_SUBSTITUTION */
2890         {
2891           peek_char = shell_getc (1);
2892           /* $(...), <(...), >(...), $((...)), ${...}, and $[...] constructs */
2893           if (peek_char == '(' ||
2894                 ((peek_char == '{' || peek_char == '[') && character == '$'))   /* ) ] } */
2895             {
2896               if (peek_char == '{')             /* } */
2897                 ttok = parse_matched_pair (cd, '{', '}', &ttoklen, P_FIRSTCLOSE);
2898               else if (peek_char == '(')                /* ) */
2899                 {
2900                   /* XXX - push and pop the `(' as a delimiter for use by
2901                      the command-oriented-history code.  This way newlines
2902                      appearing in the $(...) string get added to the
2903                      history literally rather than causing a possibly-
2904                      incorrect `;' to be added. ) */
2905                   push_delimiter (dstack, peek_char);
2906                   ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
2907                   pop_delimiter (dstack);
2908                 }
2909               else
2910                 ttok = parse_matched_pair (cd, '[', ']', &ttoklen, 0);
2911               if (ttok == &matched_pair_error)
2912                 return -1;              /* Bail immediately. */
2913               RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
2914                                       token_buffer_size,
2915                                       TOKEN_DEFAULT_GROW_SIZE);
2916               token[token_index++] = character;
2917               token[token_index++] = peek_char;
2918               strcpy (token + token_index, ttok);
2919               token_index += ttoklen;
2920               FREE (ttok);
2921               dollar_present = 1;
2922               all_digits = 0;
2923               goto next_character;
2924             }
2925           /* This handles $'...' and $"..." new-style quoted strings. */
2926           else if (character == '$' && (peek_char == '\'' || peek_char == '"'))
2927             {
2928               int first_line;
2929
2930               first_line = line_number;
2931               push_delimiter (dstack, peek_char);
2932               ttok = parse_matched_pair (peek_char, peek_char, peek_char,
2933                                          &ttoklen,
2934                                          (peek_char == '\'') ? P_ALLOWESC : 0);
2935               pop_delimiter (dstack);
2936               if (ttok == &matched_pair_error)
2937                 return -1;
2938               if (peek_char == '\'')
2939                 {
2940                   ttrans = ansiexpand (ttok, 0, ttoklen - 1, &ttranslen);
2941                   free (ttok);
2942                   /* Insert the single quotes and correctly quote any
2943                      embedded single quotes (allowed because P_ALLOWESC was
2944                      passed to parse_matched_pair). */
2945                   ttok = single_quote (ttrans);
2946                   free (ttrans);
2947                   ttrans = ttok;
2948                   ttranslen = strlen (ttrans);
2949                 }
2950               else
2951                 {
2952                   /* Try to locale-expand the converted string. */
2953                   ttrans = localeexpand (ttok, 0, ttoklen - 1, first_line, &ttranslen);
2954                   free (ttok);
2955
2956                   /* Add the double quotes back */
2957                   ttok = xmalloc (ttranslen + 3);
2958                   ttok[0] = '"';
2959                   strcpy (ttok + 1, ttrans);
2960                   ttok[ttranslen + 1] = '"';
2961                   ttok[ttranslen += 2] = '\0';
2962                   free (ttrans);
2963                   ttrans = ttok;
2964                 }
2965
2966               RESIZE_MALLOCED_BUFFER (token, token_index, ttranslen + 2,
2967                                       token_buffer_size,
2968                                       TOKEN_DEFAULT_GROW_SIZE);
2969               strcpy (token + token_index, ttrans);
2970               token_index += ttranslen;
2971               FREE (ttrans);
2972               quoted = 1;
2973               all_digits = 0;
2974               goto next_character;
2975             }
2976           /* This could eventually be extended to recognize all of the
2977              shell's single-character parameter expansions, and set flags.*/
2978           else if (character == '$' && peek_char == '$')
2979             {
2980               ttok = xmalloc (3);
2981               ttok[0] = ttok[1] = '$';
2982               ttok[2] = '\0';
2983               RESIZE_MALLOCED_BUFFER (token, token_index, 3,
2984                                       token_buffer_size,
2985                                       TOKEN_DEFAULT_GROW_SIZE);
2986               strcpy (token + token_index, ttok);
2987               token_index += 2;
2988               dollar_present = 1;
2989               all_digits = 0;
2990               FREE (ttok);
2991               goto next_character;
2992             }
2993           else
2994             shell_ungetc (peek_char);
2995         }
2996
2997 #if defined (ARRAY_VARS)
2998       /* Identify possible compound array variable assignment. */
2999       else if (character == '=' && token_index > 0)
3000         {
3001           peek_char = shell_getc (1);
3002           if (peek_char == '(')         /* ) */
3003             {
3004               ttok = parse_matched_pair (cd, '(', ')', &ttoklen, 0);
3005               if (ttok == &matched_pair_error)
3006                 return -1;              /* Bail immediately. */
3007               if (ttok[0] == '(')       /* ) */
3008                 {
3009                   FREE (ttok);
3010                   return -1;
3011                 }
3012               RESIZE_MALLOCED_BUFFER (token, token_index, ttoklen + 2,
3013                                       token_buffer_size,
3014                                       TOKEN_DEFAULT_GROW_SIZE);
3015               token[token_index++] = character;
3016               token[token_index++] = peek_char;
3017               strcpy (token + token_index, ttok);
3018               token_index += ttoklen;
3019               FREE (ttok);
3020               all_digits = 0;
3021               goto next_character;
3022             }
3023           else
3024             shell_ungetc (peek_char);
3025         }
3026 #endif
3027
3028       /* When not parsing a multi-character word construct, shell meta-
3029          characters break words. */
3030       if (shellbreak (character))
3031         {
3032           shell_ungetc (character);
3033           goto got_token;
3034         }
3035
3036     got_character:
3037
3038       all_digits &= digit (character);
3039       dollar_present |= character == '$';
3040
3041       if (character == CTLESC || character == CTLNUL)
3042         token[token_index++] = CTLESC;
3043
3044       token[token_index++] = character;
3045
3046       RESIZE_MALLOCED_BUFFER (token, token_index, 1, token_buffer_size,
3047                               TOKEN_DEFAULT_GROW_SIZE);
3048
3049     next_character:
3050       if (character == '\n' && interactive &&
3051         (bash_input.type == st_stdin || bash_input.type == st_stream))
3052         prompt_again ();
3053
3054       /* We want to remove quoted newlines (that is, a \<newline> pair)
3055          unless we are within single quotes or pass_next_character is
3056          set (the shell equivalent of literal-next). */
3057       cd = current_delimiter (dstack);
3058       character = shell_getc (cd != '\'' && pass_next_character == 0);
3059     }   /* end for (;;) */
3060
3061 got_token:
3062
3063   token[token_index] = '\0';
3064
3065   /* Check to see what thing we should return.  If the last_read_token
3066      is a `<', or a `&', or the character which ended this token is
3067      a '>' or '<', then, and ONLY then, is this input token a NUMBER.
3068      Otherwise, it is just a word, and should be returned as such. */
3069   if (all_digits && (character == '<' || character == '>' ||
3070                     last_read_token == LESS_AND ||
3071                     last_read_token == GREATER_AND))
3072       {
3073         yylval.number = atoi (token);
3074         return (NUMBER);
3075       }
3076
3077   /* Check for special case tokens. */
3078   result = special_case_tokens (token);
3079   if (result >= 0)
3080     return result;
3081
3082 #if defined (ALIAS)
3083   /* Posix.2 does not allow reserved words to be aliased, so check for all
3084      of them, including special cases, before expanding the current token
3085      as an alias. */
3086   if (posixly_correct)
3087     CHECK_FOR_RESERVED_WORD (token);
3088
3089   /* Aliases are expanded iff EXPAND_ALIASES is non-zero, and quoting
3090      inhibits alias expansion. */
3091   if (expand_aliases && quoted == 0)
3092     {
3093       result = alias_expand_token (token);
3094       if (result == RE_READ_TOKEN)
3095         return (RE_READ_TOKEN);
3096       else if (result == NO_EXPANSION)
3097         parser_state &= ~PST_ALEXPNEXT;
3098     }
3099
3100   /* If not in Posix.2 mode, check for reserved words after alias
3101      expansion. */
3102   if (posixly_correct == 0)
3103 #endif
3104     CHECK_FOR_RESERVED_WORD (token);
3105
3106   the_word = (WORD_DESC *)xmalloc (sizeof (WORD_DESC));
3107   the_word->word = xmalloc (1 + token_index);
3108   the_word->flags = 0;
3109   strcpy (the_word->word, token);
3110   if (dollar_present)
3111     the_word->flags |= W_HASDOLLAR;
3112   if (quoted)
3113     the_word->flags |= W_QUOTED;
3114   /* A word is an assignment if it appears at the beginning of a
3115      simple command, or after another assignment word.  This is
3116      context-dependent, so it cannot be handled in the grammar. */
3117   if (assignment (token))
3118     {
3119       the_word->flags |= W_ASSIGNMENT;
3120       /* Don't perform word splitting on assignment statements. */
3121       if (assignment_acceptable (last_read_token))
3122         the_word->flags |= W_NOSPLIT;
3123     }
3124
3125   yylval.word = the_word;
3126
3127   result = ((the_word->flags & (W_ASSIGNMENT|W_NOSPLIT)) == (W_ASSIGNMENT|W_NOSPLIT))
3128                 ? ASSIGNMENT_WORD : WORD;
3129
3130   if (last_read_token == FUNCTION)
3131     {
3132       parser_state |= PST_ALLOWOPNBRC;
3133       function_dstart = line_number;
3134     }
3135
3136   return (result);
3137 }
3138
3139 /* $'...' ANSI-C expand the portion of STRING between START and END and
3140    return the result.  The result cannot be longer than the input string. */
3141 static char *
3142 ansiexpand (string, start, end, lenp)
3143      char *string;
3144      int start, end, *lenp;
3145 {
3146   char *temp, *t;
3147   int len, tlen;
3148
3149   temp = xmalloc (end - start + 1);
3150   for (tlen = 0, len = start; len < end; )
3151     temp[tlen++] = string[len++];
3152   temp[tlen] = '\0';
3153
3154   if (*temp)
3155     {
3156       t = ansicstr (temp, tlen, 0, (int *)NULL, lenp);
3157       free (temp);
3158       return (t);
3159     }
3160   else
3161     {
3162       if (lenp)
3163         *lenp = 0;
3164       return (temp);
3165     }
3166 }
3167
3168 /* Change a bash string into a string suitable for inclusion in a `po' file.
3169    This backslash-escapes `"' and `\' and changes newlines into \\\n"\n". */
3170 static char *
3171 mk_msgstr (string, foundnlp)
3172      char *string;
3173      int *foundnlp;
3174 {
3175   register int c, len;
3176   char *result, *r, *s;
3177
3178   for (len = 0, s = string; s && *s; s++)
3179     {
3180       len++;
3181       if (*s == '"' || *s == '\\')
3182         len++;
3183       else if (*s == '\n')
3184         len += 5;
3185     }
3186   
3187   r = result = xmalloc (len + 3);
3188   *r++ = '"';
3189
3190   for (s = string; s && (c = *s); s++)
3191     {
3192       if (c == '\n')    /* <NL> -> \n"<NL>" */
3193         {
3194           *r++ = '\\';
3195           *r++ = 'n';
3196           *r++ = '"';
3197           *r++ = '\n';
3198           *r++ = '"';
3199           if (foundnlp)
3200             *foundnlp = 1;
3201           continue;
3202         }
3203       if (c == '"' || c == '\\')
3204         *r++ = '\\';
3205       *r++ = c;
3206     }
3207
3208   *r++ = '"';
3209   *r++ = '\0';
3210
3211   return result;
3212 }
3213
3214 /* $"..." -- Translate the portion of STRING between START and END
3215    according to current locale using gettext (if available) and return
3216    the result.  The caller will take care of leaving the quotes intact.
3217    The string will be left without the leading `$' by the caller.
3218    If translation is performed, the translated string will be double-quoted
3219    by the caller.  The length of the translated string is returned in LENP,
3220    if non-null. */
3221 static char *
3222 localeexpand (string, start, end, lineno, lenp)
3223      char *string;
3224      int start, end, lineno, *lenp;
3225 {
3226   int len, tlen, foundnl;
3227   char *temp, *t, *t2;
3228
3229   temp = xmalloc (end - start + 1);
3230   for (tlen = 0, len = start; len < end; )
3231     temp[tlen++] = string[len++];
3232   temp[tlen] = '\0';
3233
3234   /* If we're just dumping translatable strings, don't do anything with the
3235      string itself, but if we're dumping in `po' file format, convert it into a form more palatable to gettext(3)
3236      and friends by quoting `"' and `\' with backslashes and converting <NL>
3237      into `\n"<NL>"'.  If we find a newline in TEMP, we first output a
3238      `msgid ""' line and then the translated string; otherwise we output the
3239      `msgid' and translated string all on one line. */
3240   if (dump_translatable_strings)
3241     {
3242       if (dump_po_strings)
3243         {
3244           foundnl = 0;
3245           t = mk_msgstr (temp, &foundnl);
3246           t2 = foundnl ? "\"\"\n" : "";
3247
3248           printf ("#: %s:%d\nmsgid %s%s\nmsgstr \"\"\n",
3249                   (bash_input.name ? bash_input.name : "stdin"), lineno, t2, t);
3250           free (t);
3251         }
3252       else
3253         printf ("\"%s\"\n", temp);
3254
3255       if (lenp)
3256         *lenp = tlen;
3257       return (temp);
3258     }
3259   else if (*temp)
3260     {
3261       t = localetrans (temp, tlen, &len);
3262       free (temp);
3263       if (lenp)
3264         *lenp = len;
3265       return (t);
3266     }
3267   else
3268     {
3269       if (lenp)
3270         *lenp = 0;
3271       return (temp);
3272     }
3273 }
3274
3275 /* Return 1 if TOKEN is a token that after being read would allow
3276    a reserved word to be seen, else 0. */
3277 static int
3278 reserved_word_acceptable (token)
3279      int token;
3280 {
3281   if (token == '\n' || token == ';' || token == '(' || token == ')' ||
3282       token == '|' || token == '&' || token == '{' ||
3283       token == '}' ||                   /* XXX */
3284       token == AND_AND ||
3285       token == BANG ||
3286       token == TIME || token == TIMEOPT ||
3287       token == DO ||
3288       token == ELIF ||
3289       token == ELSE ||
3290       token == FI ||
3291       token == IF ||
3292       token == OR_OR ||
3293       token == SEMI_SEMI ||
3294       token == THEN ||
3295       token == UNTIL ||
3296       token == WHILE ||
3297       token == DONE ||          /* XXX these two are experimental */
3298       token == ESAC ||
3299       token == 0)
3300     return (1);
3301   else
3302     return (0);
3303 }
3304
3305 /* Return the index of TOKEN in the alist of reserved words, or -1 if
3306    TOKEN is not a shell reserved word. */
3307 int
3308 find_reserved_word (token)
3309      char *token;
3310 {
3311   int i;
3312   for (i = 0; word_token_alist[i].word; i++)
3313     if (STREQ (token, word_token_alist[i].word))
3314       return i;
3315   return -1;
3316 }
3317
3318 #if 0
3319 #if defined (READLINE)
3320 /* Called after each time readline is called.  This insures that whatever
3321    the new prompt string is gets propagated to readline's local prompt
3322    variable. */
3323 static void
3324 reset_readline_prompt ()
3325 {
3326   char *temp_prompt;
3327
3328   if (prompt_string_pointer)
3329     {
3330       temp_prompt = (*prompt_string_pointer)
3331                         ? decode_prompt_string (*prompt_string_pointer)
3332                         : (char *)NULL;
3333
3334       if (temp_prompt == 0)
3335         {
3336           temp_prompt = xmalloc (1);
3337           temp_prompt[0] = '\0';
3338         }
3339
3340       FREE (current_readline_prompt);
3341       current_readline_prompt = temp_prompt;
3342     }
3343 }
3344 #endif /* READLINE */
3345 #endif /* 0 */
3346
3347 #if defined (HISTORY)
3348 /* A list of tokens which can be followed by newlines, but not by
3349    semi-colons.  When concatenating multiple lines of history, the
3350    newline separator for such tokens is replaced with a space. */
3351 static int no_semi_successors[] = {
3352   '\n', '{', '(', ')', ';', '&', '|',
3353   CASE, DO, ELSE, IF, SEMI_SEMI, THEN, UNTIL, WHILE, AND_AND, OR_OR, IN,
3354   0
3355 };
3356
3357 /* If we are not within a delimited expression, try to be smart
3358    about which separators can be semi-colons and which must be
3359    newlines.  Returns the string that should be added into the
3360    history entry. */
3361 char *
3362 history_delimiting_chars ()
3363 {
3364   register int i;
3365
3366   if (dstack.delimiter_depth != 0)
3367     return ("\n");
3368     
3369   /* First, handle some special cases. */
3370   /*(*/
3371   /* If we just read `()', assume it's a function definition, and don't
3372      add a semicolon.  If the token before the `)' was not `(', and we're
3373      not in the midst of parsing a case statement, assume it's a
3374      parenthesized command and add the semicolon. */
3375   /*)(*/
3376   if (token_before_that == ')')
3377     {
3378       if (two_tokens_ago == '(')        /*)*/   /* function def */
3379         return " ";
3380       /* This does not work for subshells inside case statement
3381          command lists.  It's a suboptimal solution. */
3382       else if (parser_state & PST_CASESTMT)     /* case statement pattern */
3383         return " ";
3384       else      
3385         return "; ";                            /* (...) subshell */
3386     }
3387   else if (token_before_that == WORD && two_tokens_ago == FUNCTION)
3388     return " ";         /* function def using `function name' without `()' */
3389
3390   else if (token_before_that == WORD && two_tokens_ago == FOR)
3391     {
3392       /* Tricky.  `for i\nin ...' should not have a semicolon, but
3393          `for i\ndo ...' should.  We do what we can. */
3394       for (i = shell_input_line_index; whitespace(shell_input_line[i]); i++)
3395         ;
3396       if (shell_input_line[i] && shell_input_line[i] == 'i' && shell_input_line[i+1] == 'n')
3397         return " ";
3398       return ";";
3399     }
3400
3401   for (i = 0; no_semi_successors[i]; i++)
3402     {
3403       if (token_before_that == no_semi_successors[i])
3404         return (" ");
3405     }
3406
3407   return ("; ");
3408 }
3409 #endif /* HISTORY */
3410
3411 /* Issue a prompt, or prepare to issue a prompt when the next character
3412    is read. */
3413 static void
3414 prompt_again ()
3415 {
3416   char *temp_prompt;
3417
3418   if (!interactive)     /* XXX */
3419     return;
3420
3421   ps1_prompt = get_string_value ("PS1");
3422   ps2_prompt = get_string_value ("PS2");
3423
3424   if (!prompt_string_pointer)
3425     prompt_string_pointer = &ps1_prompt;
3426
3427   temp_prompt = *prompt_string_pointer
3428                         ? decode_prompt_string (*prompt_string_pointer)
3429                         : (char *)NULL;
3430
3431   if (temp_prompt == 0)
3432     {
3433       temp_prompt = xmalloc (1);
3434       temp_prompt[0] = '\0';
3435     }
3436
3437   current_prompt_string = *prompt_string_pointer;
3438   prompt_string_pointer = &ps2_prompt;
3439
3440 #if defined (READLINE)
3441   if (!no_line_editing)
3442     {
3443       FREE (current_readline_prompt);
3444       current_readline_prompt = temp_prompt;
3445     }
3446   else
3447 #endif  /* READLINE */
3448     {
3449       FREE (current_decoded_prompt);
3450       current_decoded_prompt = temp_prompt;
3451     }
3452 }
3453
3454 int
3455 get_current_prompt_level ()
3456 {
3457   return ((current_prompt_string && current_prompt_string == ps2_prompt) ? 2 : 1);
3458 }
3459
3460 void
3461 set_current_prompt_level (x)
3462      int x;
3463 {
3464   prompt_string_pointer = (x == 2) ? &ps2_prompt : &ps1_prompt;
3465   current_prompt_string = *prompt_string_pointer;
3466 }
3467       
3468 static void
3469 print_prompt ()
3470 {
3471   fprintf (stderr, "%s", current_decoded_prompt);
3472   fflush (stderr);
3473 }
3474
3475 /* Return a string which will be printed as a prompt.  The string
3476    may contain special characters which are decoded as follows:
3477
3478         \a      bell (ascii 07)
3479         \e      escape (ascii 033)
3480         \d      the date in Day Mon Date format
3481         \h      the hostname up to the first `.'
3482         \H      the hostname
3483         \j      the number of active jobs
3484         \l      the basename of the shell's tty device name
3485         \n      CRLF
3486         \s      the name of the shell
3487         \t      the time in 24-hour hh:mm:ss format
3488         \T      the time in 12-hour hh:mm:ss format
3489         \@      the time in 12-hour am/pm format
3490         \v      the version of bash (e.g., 2.00)
3491         \V      the release of bash, version + patchlevel (e.g., 2.00.0)
3492         \w      the current working directory
3493         \W      the last element of $PWD
3494         \u      your username
3495         \#      the command number of this command
3496         \!      the history number of this command
3497         \$      a $ or a # if you are root
3498         \nnn    character code nnn in octal
3499         \\      a backslash
3500         \[      begin a sequence of non-printing chars
3501         \]      end a sequence of non-printing chars
3502 */
3503 #define PROMPT_GROWTH 48
3504 char *
3505 decode_prompt_string (string)
3506      char *string;
3507 {
3508   WORD_LIST *list;
3509   char *result, *t;
3510   struct dstack save_dstack;
3511 #if defined (PROMPT_STRING_DECODE)
3512   int result_size, result_index;
3513   int c, n;
3514   char *temp, octal_string[4];
3515   time_t the_time;
3516
3517   result = xmalloc (result_size = PROMPT_GROWTH);
3518   result[result_index = 0] = 0;
3519   temp = (char *)NULL;
3520
3521   while (c = *string++)
3522     {
3523       if (posixly_correct && c == '!')
3524         {
3525           if (*string == '!')
3526             {
3527               temp = savestring ("!");
3528               goto add_string;
3529             }
3530           else
3531             {
3532 #if !defined (HISTORY)
3533                 temp = savestring ("1");
3534 #else /* HISTORY */
3535                 temp = itos (history_number ());
3536 #endif /* HISTORY */
3537                 string--;       /* add_string increments string again. */
3538                 goto add_string;
3539             }
3540         }
3541       if (c == '\\')
3542         {
3543           c = *string;
3544
3545           switch (c)
3546             {
3547             case '0':
3548             case '1':
3549             case '2':
3550             case '3':
3551             case '4':
3552             case '5':
3553             case '6':
3554             case '7':
3555               strncpy (octal_string, string, 3);
3556               octal_string[3] = '\0';
3557
3558               n = read_octal (octal_string);
3559               temp = xmalloc (3);
3560
3561               if (n == CTLESC || n == CTLNUL)
3562                 {
3563                   string += 3;
3564                   temp[0] = CTLESC;
3565                   temp[1] = n;
3566                   temp[2] = '\0';
3567                 }
3568               else if (n == -1)
3569                 {
3570                   temp[0] = '\\';
3571                   temp[1] = '\0';
3572                 }
3573               else
3574                 {
3575                   string += 3;
3576                   temp[0] = n;
3577                   temp[1] = '\0';
3578                 }
3579
3580               c = 0;
3581               goto add_string;
3582
3583             case 't':
3584             case 'd':
3585             case 'T':
3586             case '@':
3587               /* Make the current time/date into a string. */
3588               the_time = time (0);
3589               temp = ctime (&the_time);
3590
3591               temp = (c != 'd') ? savestring (temp + 11) : savestring (temp);
3592               temp[(c != 'd') ? 8 : 10] = '\0';
3593
3594               /* quick and dirty conversion to 12-hour time */
3595               if (c == 'T' || c == '@')
3596                 {
3597                   if (c == '@')
3598                     {
3599                       temp[5] = 'a';    /* am/pm format */
3600                       temp[6] = 'm';
3601                       temp[7] = '\0';
3602                     }
3603                   c = temp[2];
3604                   temp[2] = '\0';
3605                   n = atoi (temp);
3606                   temp[2] = c;
3607                   n -= 12;
3608                   if (n > 0)
3609                     {
3610                       temp[0] = (n / 10) + '0';
3611                       temp[1] = (n % 10) + '0';
3612                     }
3613                   if (n >= 0 && temp[5] == 'a')
3614                     temp[5] = 'p';
3615                 }
3616               goto add_string;
3617
3618             case 'r':
3619               temp = xmalloc (2);
3620               temp[0] = '\r';
3621               temp[1] = '\0';
3622               goto add_string;
3623
3624             case 'n':
3625               temp = xmalloc (3);
3626               temp[0] = no_line_editing ? '\n' : '\r';
3627               temp[1] = no_line_editing ? '\0' : '\n';
3628               temp[2] = '\0';
3629               goto add_string;
3630
3631             case 's':
3632               temp = base_pathname (shell_name);
3633               temp = savestring (temp);
3634               goto add_string;
3635
3636             case 'v':
3637             case 'V':
3638               temp = xmalloc (8);
3639               if (c == 'v')
3640                 strcpy (temp, dist_version);
3641               else
3642                 sprintf (temp, "%s.%d", dist_version, patch_level);
3643               goto add_string;
3644
3645             case 'w':
3646             case 'W':
3647               {
3648                 /* Use the value of PWD because it is much more efficient. */
3649                 char t_string[PATH_MAX];
3650                 int tlen;
3651
3652                 temp = get_string_value ("PWD");
3653
3654                 if (temp == 0)
3655                   {
3656                     if (getcwd (t_string, sizeof(t_string)) == 0)
3657                       {
3658                         t_string[0] = '.';
3659                         tlen = 1;
3660                       }
3661                     else
3662                       tlen = strlen (t_string);
3663                   }
3664                 else
3665                   {
3666                     tlen = sizeof (t_string) - 1;
3667                     strncpy (t_string, temp, tlen);
3668                   }
3669                 t_string[tlen] = '\0';
3670
3671                 if (c == 'W')
3672                   {
3673                     t = strrchr (t_string, '/');
3674                     if (t && t != t_string)
3675                       strcpy (t_string, t + 1);
3676                   }
3677                 else
3678                   /* polite_directory_format is guaranteed to return a string
3679                      no longer than PATH_MAX - 1 characters. */
3680                   strcpy (t_string, polite_directory_format (t_string));
3681
3682                 /* If we're going to be expanding the prompt string later,
3683                    quote the directory name. */
3684                 if (promptvars || posixly_correct)
3685 #if 0
3686                   temp = backslash_quote (t_string);
3687 #else
3688                   /* Make sure that expand_prompt_string is called with a
3689                      second argument of Q_DOUBLE_QUOTE if we use this
3690                      function here. */
3691                   temp = backslash_quote_for_double_quotes (t_string);
3692 #endif
3693                 else
3694                   temp = savestring (t_string);
3695
3696                 goto add_string;
3697               }
3698
3699             case 'u':
3700               if (current_user.user_name == 0)
3701                 get_current_user_info ();
3702               temp = savestring (current_user.user_name);
3703               goto add_string;
3704
3705             case 'h':
3706             case 'H':
3707               temp = savestring (current_host_name);
3708               if (c == 'h' && (t = (char *)strchr (temp, '.')))
3709                 *t = '\0';
3710               goto add_string;
3711
3712             case '#':
3713               temp = itos (current_command_number);
3714               goto add_string;
3715
3716             case '!':
3717 #if !defined (HISTORY)
3718               temp = savestring ("1");
3719 #else /* HISTORY */
3720               temp = itos (history_number ());
3721 #endif /* HISTORY */
3722               goto add_string;
3723
3724             case '$':
3725               t = temp = xmalloc (3);
3726               if ((promptvars || posixly_correct) && (current_user.euid != 0))
3727                 *t++ = '\\';
3728               *t++ = current_user.euid == 0 ? '#' : '$';
3729               *t = '\0';
3730               goto add_string;
3731
3732             case 'j':
3733               temp = itos (count_all_jobs ());
3734               goto add_string;
3735
3736             case 'l':
3737 #if defined (HAVE_TTYNAME)
3738               temp = (char *)ttyname (fileno (stdin));
3739               t = temp ? base_pathname (temp) : "tty";
3740               temp = savestring (t);
3741 #else
3742               temp = savestring ("tty");
3743 #endif /* !HAVE_TTYNAME */
3744               goto add_string;
3745
3746 #if defined (READLINE)
3747             case '[':
3748             case ']':
3749               temp = xmalloc (3);
3750               temp[0] = '\001';
3751               temp[1] = (c == '[') ? RL_PROMPT_START_IGNORE : RL_PROMPT_END_IGNORE;
3752               temp[2] = '\0';
3753               goto add_string;
3754 #endif /* READLINE */
3755
3756             case '\\':
3757               temp = xmalloc (2);
3758               temp[0] = c;
3759               temp[1] = '\0';
3760               goto add_string;
3761
3762             case 'a':
3763             case 'e':
3764               temp = xmalloc (2);
3765               temp[0] = (c == 'a') ? '\07' : '\033';
3766               temp[1] = '\0';
3767               goto add_string;
3768
3769             default:
3770               temp = xmalloc (3);
3771               temp[0] = '\\';
3772               temp[1] = c;
3773               temp[2] = '\0';
3774
3775             add_string:
3776               if (c)
3777                 string++;
3778               result =
3779                 sub_append_string (temp, result, &result_index, &result_size);
3780               temp = (char *)NULL; /* Freed in sub_append_string (). */
3781               result[result_index] = '\0';
3782               break;
3783             }
3784         }
3785       else
3786         {
3787           RESIZE_MALLOCED_BUFFER (result, result_index, 3, result_size, PROMPT_GROWTH);
3788           result[result_index++] = c;
3789           result[result_index] = '\0';
3790         }
3791     }
3792 #else /* !PROMPT_STRING_DECODE */
3793   result = savestring (string);
3794 #endif /* !PROMPT_STRING_DECODE */
3795
3796   /* Save the delimiter stack and point `dstack' to temp space so any
3797      command substitutions in the prompt string won't result in screwing
3798      up the parser's quoting state. */
3799   save_dstack = dstack;
3800   dstack = temp_dstack;
3801   dstack.delimiter_depth = 0;
3802
3803   /* Perform variable and parameter expansion and command substitution on
3804      the prompt string. */
3805   if (promptvars || posixly_correct)
3806     {
3807 #if 0
3808       list = expand_string_unsplit (result, Q_DOUBLE_QUOTES);
3809 #else
3810       list = expand_prompt_string (result, Q_DOUBLE_QUOTES);
3811 #endif
3812       free (result);
3813       result = string_list (list);
3814       dispose_words (list);
3815     }
3816   else
3817     {
3818       t = dequote_string (result);
3819       free (result);
3820       result = t;
3821     }
3822
3823   dstack = save_dstack;
3824
3825   return (result);
3826 }
3827
3828 /* Report a syntax error, and restart the parser.  Call here for fatal
3829    errors. */
3830 int
3831 yyerror ()
3832 {
3833   report_syntax_error ((char *)NULL);
3834   reset_parser ();
3835   return (0);
3836 }
3837
3838 /* Report a syntax error with line numbers, etc.
3839    Call here for recoverable errors.  If you have a message to print,
3840    then place it in MESSAGE, otherwise pass NULL and this will figure
3841    out an appropriate message for you. */
3842 static void
3843 report_syntax_error (message)
3844      char *message;
3845 {
3846   char *msg, *t;
3847   int token_end, i;
3848   char msg2[2];
3849
3850   if (message)
3851     {
3852       parser_error (line_number, "%s", message);
3853       if (interactive && EOF_Reached)
3854         EOF_Reached = 0;
3855       last_command_exit_value = EX_USAGE;
3856       return;
3857     }
3858
3859   /* If the line of input we're reading is not null, try to find the
3860      objectionable token. */
3861   if (shell_input_line && *shell_input_line)
3862     {
3863       t = shell_input_line;
3864       i = shell_input_line_index;
3865       token_end = 0;
3866
3867       if (i && t[i] == '\0')
3868         i--;
3869
3870       while (i && (whitespace (t[i]) || t[i] == '\n'))
3871         i--;
3872
3873       if (i)
3874         token_end = i + 1;
3875
3876       while (i && (member (t[i], " \n\t;|&") == 0))
3877         i--;
3878
3879       while (i != token_end && (whitespace (t[i]) || t[i] == '\n'))
3880         i++;
3881
3882       /* Print the offending token. */
3883       if (token_end || (i == 0 && token_end == 0))
3884         {
3885           if (token_end)
3886             msg = substring (t, i, token_end);
3887           else  /* one-character token */
3888             {
3889               msg2[0] = t[i];
3890               msg2[1] = '\0';
3891               msg = msg2;
3892             }
3893
3894           parser_error (line_number, "syntax error near unexpected token `%s'", msg);
3895
3896           if (msg != msg2)
3897             free (msg);
3898         }
3899
3900       /* If not interactive, print the line containing the error. */
3901       if (interactive == 0)
3902         {
3903           msg = savestring (shell_input_line);
3904           token_end = strlen (msg);
3905           while (token_end && msg[token_end - 1] == '\n')
3906             msg[--token_end] = '\0';
3907
3908           parser_error (line_number, "`%s'", msg);
3909           free (msg);
3910         }
3911     }
3912   else
3913     {
3914       msg = EOF_Reached ? "syntax error: unexpected end of file" : "syntax error";
3915       parser_error (line_number, "%s", msg);
3916       /* When the shell is interactive, this file uses EOF_Reached
3917          only for error reporting.  Other mechanisms are used to
3918          decide whether or not to exit. */
3919       if (interactive && EOF_Reached)
3920         EOF_Reached = 0;
3921     }
3922   last_command_exit_value = EX_USAGE;
3923 }
3924
3925 /* ??? Needed function. ??? We have to be able to discard the constructs
3926    created during parsing.  In the case of error, we want to return
3927    allocated objects to the memory pool.  In the case of no error, we want
3928    to throw away the information about where the allocated objects live.
3929    (dispose_command () will actually free the command. */
3930 static void
3931 discard_parser_constructs (error_p)
3932      int error_p;
3933 {
3934 }
3935
3936 /* Do that silly `type "bye" to exit' stuff.  You know, "ignoreeof". */
3937
3938 /* A flag denoting whether or not ignoreeof is set. */
3939 int ignoreeof = 0;
3940
3941 /* The number of times that we have encountered an EOF character without
3942    another character intervening.  When this gets above the limit, the
3943    shell terminates. */
3944 int eof_encountered = 0;
3945
3946 /* The limit for eof_encountered. */
3947 int eof_encountered_limit = 10;
3948
3949 /* If we have EOF as the only input unit, this user wants to leave
3950    the shell.  If the shell is not interactive, then just leave.
3951    Otherwise, if ignoreeof is set, and we haven't done this the
3952    required number of times in a row, print a message. */
3953 static void
3954 handle_eof_input_unit ()
3955 {
3956   if (interactive)
3957     {
3958       /* shell.c may use this to decide whether or not to write out the
3959          history, among other things.  We use it only for error reporting
3960          in this file. */
3961       if (EOF_Reached)
3962         EOF_Reached = 0;
3963
3964       /* If the user wants to "ignore" eof, then let her do so, kind of. */
3965       if (ignoreeof)
3966         {
3967           if (eof_encountered < eof_encountered_limit)
3968             {
3969               fprintf (stderr, "Use \"%s\" to leave the shell.\n",
3970                        login_shell ? "logout" : "exit");
3971               eof_encountered++;
3972               /* Reset the prompt string to be $PS1. */
3973               prompt_string_pointer = (char **)NULL;
3974               prompt_again ();
3975               last_read_token = current_token = '\n';
3976               return;
3977             }
3978         }
3979
3980       /* In this case EOF should exit the shell.  Do it now. */
3981       reset_parser ();
3982       exit_builtin ((WORD_LIST *)NULL);
3983     }
3984   else
3985     {
3986       /* We don't write history files, etc., for non-interactive shells. */
3987       EOF_Reached = 1;
3988     }
3989 }
3990
3991 static WORD_LIST parse_string_error;
3992
3993 /* Take a string and run it through the shell parser, returning the
3994    resultant word list.  Used by compound array assignment. */
3995 WORD_LIST *
3996 parse_string_to_word_list (s, whom)
3997      char *s, *whom;
3998 {
3999   WORD_LIST *wl;
4000   int tok, orig_line_number, orig_input_terminator;
4001 #if defined (HISTORY)
4002   int old_remember_on_history, old_history_expansion_inhibited;
4003 #endif
4004
4005 #if defined (HISTORY)
4006   old_remember_on_history = remember_on_history;
4007 #  if defined (BANG_HISTORY)
4008   old_history_expansion_inhibited = history_expansion_inhibited;
4009 #  endif
4010   bash_history_disable ();
4011 #endif
4012
4013   orig_line_number = line_number;
4014   orig_input_terminator = shell_input_line_terminator;
4015
4016   push_stream (1);
4017   last_read_token = '\n';
4018
4019   with_input_from_string (s, whom);
4020   wl = (WORD_LIST *)NULL;
4021   while ((tok = read_token (READ)) != yacc_EOF)
4022     {
4023       if (tok == '\n' && *bash_input.location.string == '\0')
4024         break;
4025       if (tok != WORD && tok != ASSIGNMENT_WORD)
4026         {
4027           line_number = orig_line_number + line_number - 1;
4028           yyerror ();   /* does the right thing */
4029           if (wl)
4030             dispose_words (wl);
4031           wl = &parse_string_error;
4032           break;
4033         }
4034       wl = make_word_list (yylval.word, wl);
4035     }
4036   
4037   last_read_token = '\n';
4038   pop_stream ();
4039
4040 #if defined (HISTORY)
4041   remember_on_history = old_remember_on_history;
4042 #  if defined (BANG_HISTORY)
4043   history_expansion_inhibited = old_history_expansion_inhibited;
4044 #  endif /* BANG_HISTORY */
4045 #endif /* HISTORY */
4046
4047   shell_input_line_terminator = orig_input_terminator;
4048
4049   if (wl == &parse_string_error)
4050     {
4051       last_command_exit_value = EXECUTION_FAILURE;
4052       if (interactive_shell == 0 && posixly_correct)
4053         jump_to_top_level (FORCE_EOF);
4054       else
4055         jump_to_top_level (DISCARD);
4056     }
4057
4058   return (REVERSE_LIST (wl, WORD_LIST *));
4059 }