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