Imported from ../bash-4.0-rc1.tar.gz.
[platform/upstream/bash.git] / subst.c
diff --git a/subst.c b/subst.c
index fcc024b..13e960d 100644 (file)
--- a/subst.c
+++ b/subst.c
@@ -1,33 +1,35 @@
-/* subst.c -- The part of the shell that does parameter, command, and
-   globbing substitutions. */
+/* subst.c -- The part of the shell that does parameter, command, arithmetic,
+   and globbing substitutions. */
 
 /* ``Have a little faith, there's magic in the night.  You ain't a
      beauty, but, hey, you're alright.'' */
 
-/* Copyright (C) 1987-2004 Free Software Foundation, Inc.
+/* Copyright (C) 1987-2009 Free Software Foundation, Inc.
 
    This file is part of GNU Bash, the Bourne Again SHell.
 
-   Bash is free software; you can redistribute it and/or modify it under
-   the terms of the GNU General Public License as published by the Free
-   Software Foundation; either version 2, or (at your option) any later
-   version.
+   Bash is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
 
-   Bash is distributed in the hope that it will be useful, but WITHOUT ANY
-   WARRANTY; without even the implied warranty of MERCHANTABILITY or
-   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-   for more details.
+   Bash is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
 
-   You should have received a copy of the GNU General Public License along
-   with Bash; see the file COPYING.  If not, write to the Free Software
-   Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
+   You should have received a copy of the GNU General Public License
+   along with Bash.  If not, see <http://www.gnu.org/licenses/>.
+*/
 
 #include "config.h"
 
 #include "bashtypes.h"
 #include <stdio.h>
 #include "chartypes.h"
-#include <pwd.h>
+#if defined (HAVE_PWD_H)
+#  include <pwd.h>
+#endif
 #include <signal.h>
 #include <errno.h>
 
@@ -53,6 +55,8 @@
 #include "builtins/getopt.h"
 #include "builtins/common.h"
 
+#include "builtins/builtext.h"
+
 #include <tilde/tilde.h>
 #include <glob/strmatch.h>
 
@@ -69,6 +73,7 @@ extern int errno;
 #define VT_POSPARMS    1
 #define VT_ARRAYVAR    2
 #define VT_ARRAYMEMBER 3
+#define VT_ASSOCVAR    4
 
 #define VT_STARSUB     128     /* $* or ${array[*]} -- used to split */
 
@@ -78,10 +83,6 @@ extern int errno;
 #define ST_SQUOTE      0x04    /* unused yet */
 #define ST_DQUOTE      0x08    /* unused yet */
 
-/* Flags for the string extraction functions. */
-#define EX_NOALLOC     0x01    /* just skip; don't return substring */
-#define EX_VARNAME     0x02    /* variable name; for string_extract () */
-
 /* Flags for the `pflags' argument to param_expand() */
 #define PF_NOCOMSUB    0x01    /* Do not perform command substitution */
 
@@ -124,12 +125,20 @@ pid_t current_command_subst_pid = NO_PID;
 SHELL_VAR *ifs_var;
 char *ifs_value;
 unsigned char ifs_cmap[UCHAR_MAX + 1];
+
+#if defined (HANDLE_MULTIBYTE)
+unsigned char ifs_firstc[MB_LEN_MAX];
+size_t ifs_firstc_len;
+#else
 unsigned char ifs_firstc;
+#endif
+
+int assigning_in_environment;
 
 /* Extern functions and variables from different files. */
 extern int last_command_exit_value, last_command_exit_signal;
 extern int subshell_environment;
-extern int subshell_level;
+extern int subshell_level, parse_and_execute_level;
 extern int eof_encountered;
 extern int return_catch_flag, return_catch_value;
 extern pid_t dollar_dollar_pid;
@@ -140,6 +149,10 @@ extern int wordexp_only;
 extern int expanding_redir;
 extern int tempenv_assign_error;
 
+#if !defined (HAVE_WCSDUP) && defined (HANDLE_MULTIBYTE)
+extern wchar_t *wcsdup __P((const wchar_t *));
+#endif
+
 /* Non-zero means to allow unmatched globbed filenames to expand to
    a null file. */
 int allow_null_glob_expansion;
@@ -157,7 +170,9 @@ static int glob_argv_flags_size;
 #endif
 
 static WORD_LIST expand_word_error, expand_word_fatal;
+static WORD_DESC expand_wdesc_error, expand_wdesc_fatal;
 static char expand_param_error, expand_param_fatal;
+static char extract_string_error, extract_string_fatal;
 
 /* Tell the expansion functions to not longjmp back to top_level on fatal
    errors.  Enabled when doing completion and prompt string expansion. */
@@ -188,23 +203,22 @@ static WORD_LIST *expand_string_leave_quoted __P((char *, int));
 static WORD_LIST *expand_string_for_rhs __P((char *, int, int *, int *));
 
 static WORD_LIST *list_quote_escapes __P((WORD_LIST *));
-static char *dequote_escapes __P((char *));
 static char *make_quoted_char __P((int));
 static WORD_LIST *quote_list __P((WORD_LIST *));
-static WORD_LIST *dequote_list __P((WORD_LIST *));
-static char *remove_quoted_escapes __P((char *));
-static char *remove_quoted_nulls __P((char *));
 
 static int unquoted_substring __P((char *, char *));
 static int unquoted_member __P((int, char *));
 
-static int do_assignment_internal __P((const char *, int));
+#if defined (ARRAY_VARS)
+static SHELL_VAR *do_compound_assignment __P((char *, char *, int));
+#endif
+static int do_assignment_internal __P((const WORD_DESC *, int));
 
-static char *string_extract_verbatim __P((char *, int *, char *));
+static char *string_extract_verbatim __P((char *, size_t, int *, char *, int));
 static char *string_extract __P((char *, int *, char *, int));
 static char *string_extract_double_quoted __P((char *, int *, int));
 static inline char *string_extract_single_quoted __P((char *, int *));
-static inline int skip_single_quoted __P((char *, size_t, int));
+static inline int skip_single_quoted __P((const char *, size_t, int));
 static int skip_double_quoted __P((char *, size_t, int));
 static char *extract_delimited_string __P((char *, int *, char *, char *, char *, int));
 static char *extract_dollar_brace_string __P((char *, int *, int, int));
@@ -214,10 +228,7 @@ static char *pos_params __P((char *, int, int, int));
 static unsigned char *mb_getcharlens __P((char *, int));
 
 static char *remove_upattern __P((char *, char *, int));
-#if defined (HANDLE_MULTIBYTE)
-#  if !defined (HAVE_WCSDUP)
-static wchar_t *wcsdup __P((wchar_t *));
-#  endif
+#if defined (HANDLE_MULTIBYTE) 
 static wchar_t *remove_wpattern __P((wchar_t *, size_t, wchar_t *, int));
 #endif
 static char *remove_pattern __P((char *, char *, int));
@@ -235,13 +246,13 @@ static char *variable_remove_pattern __P((char *, char *, int, int));
 static char *list_remove_pattern __P((WORD_LIST *, char *, int, int, int));
 static char *parameter_list_remove_pattern __P((int, char *, int, int));
 #ifdef ARRAY_VARS
-static char *array_remove_pattern __P((ARRAY *, char *, int, char *, int));
+static char *array_remove_pattern __P((SHELL_VAR *, char *, int, char *, int));
 #endif
 static char *parameter_brace_remove_pattern __P((char *, char *, char *, int, int));
 
 static char *process_substitute __P((char *, int));
 
-static char *read_comsub __P((int, int));
+static char *read_comsub __P((int, int, int *));
 
 #ifdef ARRAY_VARS
 static arrayind_t array_length_reference __P((char *));
@@ -249,17 +260,18 @@ static arrayind_t array_length_reference __P((char *));
 
 static int valid_brace_expansion_word __P((char *, int));
 static int chk_atstar __P((char *, int, int *, int *));
+static int chk_arithsub __P((const char *, int));
 
-static char *parameter_brace_expand_word __P((char *, int, int));
-static char *parameter_brace_expand_indir __P((char *, int, int, int *, int *));
-static char *parameter_brace_expand_rhs __P((char *, char *, int, int, int *, int *));
+static WORD_DESC *parameter_brace_expand_word __P((char *, int, int));
+static WORD_DESC *parameter_brace_expand_indir __P((char *, int, int, int *, int *));
+static WORD_DESC *parameter_brace_expand_rhs __P((char *, char *, int, int, int *, int *));
 static void parameter_brace_expand_error __P((char *, char *));
 
 static int valid_length_expression __P((char *));
 static intmax_t parameter_brace_expand_length __P((char *));
 
 static char *skiparith __P((char *, int));
-static int verify_substring_values __P((char *, char *, int, intmax_t *, intmax_t *));
+static int verify_substring_values __P((SHELL_VAR *, char *, char *, int, intmax_t *, intmax_t *));
 static int get_var_and_type __P((char *, char *, int, SHELL_VAR **, char **));
 static char *mb_substring __P((char *, int, int));
 static char *parameter_brace_substring __P((char *, char *, char *, int));
@@ -268,8 +280,11 @@ static char *pos_params_pat_subst __P((char *, char *, char *, int));
 
 static char *parameter_brace_patsub __P((char *, char *, char *, int));
 
-static char *parameter_brace_expand __P((char *, int *, int, int *, int *));
-static char *param_expand __P((char *, int *, int, int *, int *, int *, int *, int));
+static char *pos_params_casemod __P((char *, char *, int, int));
+static char *parameter_brace_casemod __P((char *, char *, int, char *, int));
+
+static WORD_DESC *parameter_brace_expand __P((char *, int *, int, int *, int *));
+static WORD_DESC *param_expand __P((char *, int *, int, int *, int *, int *, int *, int));
 
 static WORD_LIST *expand_word_internal __P((WORD_DESC *, int, int, int *, int *));
 
@@ -282,6 +297,9 @@ static WORD_LIST *glob_expand_word_list __P((WORD_LIST *, int));
 #ifdef BRACE_EXPANSION
 static WORD_LIST *brace_expand_word_list __P((WORD_LIST *, int));
 #endif
+#if defined (ARRAY_VARS)
+static int make_internal_declare __P((char *, char *));
+#endif
 static WORD_LIST *shell_expand_word_list __P((WORD_LIST *, int));
 static WORD_LIST *expand_word_list_internal __P((WORD_LIST *, int));
 
@@ -529,11 +547,12 @@ sub_append_number (number, target, indx, size)
 /* Extract a substring from STRING, starting at SINDEX and ending with
    one of the characters in CHARLIST.  Don't make the ending character
    part of the string.  Leave SINDEX pointing at the ending character.
-   Understand about backslashes in the string.  If (flags & EX_VARNAME)
+   Understand about backslashes in the string.  If (flags & SX_VARNAME)
    is non-zero, and array variables have been compiled into the shell,
    everything between a `[' and a corresponding `]' is skipped over.
-   If (flags & EX_NOALLOC) is non-zero, don't return the substring, just
-   update SINDEX. */
+   If (flags & SX_NOALLOC) is non-zero, don't return the substring, just
+   update SINDEX.  If (flags & SX_REQMATCH) is non-zero, the string must
+   contain a closing character from CHARLIST. */
 static char *
 string_extract (string, sindex, charlist, flags)
      char *string;
@@ -542,12 +561,14 @@ string_extract (string, sindex, charlist, flags)
      int flags;
 {
   register int c, i;
+  int found;
   size_t slen;
   char *temp;
   DECLARE_MBSTATE;
 
-  slen = strlen (string + *sindex) + *sindex;
+  slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
   i = *sindex;
+  found = 0;
   while (c = string[i])
     {
       if (c == '\\')
@@ -558,7 +579,7 @@ string_extract (string, sindex, charlist, flags)
            break;
        }
 #if defined (ARRAY_VARS)
-      else if ((flags & EX_VARNAME) && c == '[')
+      else if ((flags & SX_VARNAME) && c == '[')
        {
          int ni;
          /* If this is an array subscript, skip over it and continue. */
@@ -568,13 +589,25 @@ string_extract (string, sindex, charlist, flags)
        }
 #endif
       else if (MEMBER (c, charlist))
+       {
+         found = 1;
          break;
+       }
 
       ADVANCE_CHAR (string, slen, i);
     }
 
-  temp = (flags & EX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
+  /* If we had to have a matching delimiter and didn't find one, return an
+     error and let the caller deal with it. */
+  if ((flags & SX_REQMATCH) && found == 0)
+    {
+      *sindex = i;
+      return (&extract_string_error);
+    }
+  
+  temp = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
   *sindex = i;
+  
   return (temp);
 }
 
@@ -683,7 +716,7 @@ add_one_character:
 
          si = i + 2;
          if (string[i + 1] == LPAREN)
-           ret = extract_delimited_string (string, &si, "$(", "(", ")", 0); /*)*/
+           ret = extract_command_subst (string, &si, 0);
          else
            ret = extract_dollar_brace_string (string, &si, 1, 0);
 
@@ -785,9 +818,9 @@ skip_double_quoted (string, slen, sind)
        {
          si = i + 2;
          if (string[i + 1] == LPAREN)
-           ret = extract_delimited_string (string, &si, "$(", "(", ")", EX_NOALLOC);
+           ret = extract_command_subst (string, &si, SX_NOALLOC);
          else
-           ret = extract_dollar_brace_string (string, &si, 0, EX_NOALLOC);
+           ret = extract_dollar_brace_string (string, &si, 1, SX_NOALLOC);
 
          i = si + 1;
          continue;
@@ -821,7 +854,8 @@ string_extract_single_quoted (string, sindex)
   char *t;
   DECLARE_MBSTATE;
 
-  slen = strlen (string + *sindex) + *sindex;
+  /* Don't need slen for ADVANCE_CHAR unless multibyte chars possible. */
+  slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
   i = *sindex;
   while (string[i] && string[i] != '\'')
     ADVANCE_CHAR (string, slen, i);
@@ -837,7 +871,7 @@ string_extract_single_quoted (string, sindex)
 
 static inline int
 skip_single_quoted (string, slen, sind)
-     char *string;
+     const char *string;
      size_t slen;
      int sind;
 {
@@ -856,14 +890,21 @@ skip_single_quoted (string, slen, sind)
 /* Just like string_extract, but doesn't hack backslashes or any of
    that other stuff.  Obeys CTLESC quoting.  Used to do splitting on $IFS. */
 static char *
-string_extract_verbatim (string, sindex, charlist)
+string_extract_verbatim (string, slen, sindex, charlist, flags)
      char *string;
+     size_t slen;
      int *sindex;
      char *charlist;
+     int flags;
 {
   register int i = *sindex;
+#if defined (HANDLE_MULTIBYTE)
+  size_t clen;
+  wchar_t *wcharlist;
+#endif
   int c;
   char *temp;
+  DECLARE_MBSTATE;
 
   if (charlist[0] == '\'' && charlist[1] == '\0')
     {
@@ -872,18 +913,74 @@ string_extract_verbatim (string, sindex, charlist)
       return temp;
     }
 
-  for (i = *sindex; c = string[i]; i++)
+  i = *sindex;
+#if 0
+  /* See how the MBLEN and ADVANCE_CHAR macros work to understand why we need
+     this only if MB_CUR_MAX > 1. */
+  slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 1;
+#endif
+#if defined (HANDLE_MULTIBYTE)
+  clen = strlen (charlist);
+  wcharlist = 0;
+#endif
+  while (c = string[i])
     {
-      if (c == CTLESC)
+#if defined (HANDLE_MULTIBYTE)
+      size_t mblength;
+#endif
+      if ((flags & SX_NOCTLESC) == 0 && c == CTLESC)
        {
-         i++;
+         i += 2;
+         continue;
+       }
+      /* Even if flags contains SX_NOCTLESC, we let CTLESC quoting CTLNUL
+        through, to protect the CTLNULs from later calls to
+        remove_quoted_nulls. */
+      else if ((flags & SX_NOESCCTLNUL) == 0 && c == CTLESC && string[i+1] == CTLNUL)
+       {
+         i += 2;
          continue;
        }
 
+#if defined (HANDLE_MULTIBYTE)
+      mblength = MBLEN (string + i, slen - i);
+      if (mblength > 1)
+       {
+         wchar_t wc;
+         mblength = mbtowc (&wc, string + i, slen - i);
+         if (MB_INVALIDCH (mblength))
+           {
+             if (MEMBER (c, charlist))
+               break;
+           }
+         else
+           {
+             if (wcharlist == 0)
+               {
+                 size_t len;
+                 len = mbstowcs (wcharlist, charlist, 0);
+                 if (len == -1)
+                   len = 0;
+                 wcharlist = (wchar_t *)xmalloc (sizeof (wchar_t) * (len + 1));
+                 mbstowcs (wcharlist, charlist, len + 1);
+               }
+
+             if (wcschr (wcharlist, wc))
+               break;
+           }
+       }
+      else             
+#endif
       if (MEMBER (c, charlist))
        break;
+
+      ADVANCE_CHAR (string, slen, i);
     }
 
+#if defined (HANDLE_MULTIBYTE)
+  FREE (wcharlist);
+#endif
+
   temp = substring (string, *sindex, i);
   *sindex = i;
 
@@ -892,13 +989,21 @@ string_extract_verbatim (string, sindex, charlist)
 
 /* Extract the $( construct in STRING, and return a new string.
    Start extracting at (SINDEX) as if we had just seen "$(".
-   Make (SINDEX) get the position of the matching ")". */
+   Make (SINDEX) get the position of the matching ")". )
+   XFLAGS is additional flags to pass to other extraction functions, */
 char *
-extract_command_subst (string, sindex)
+extract_command_subst (string, sindex, xflags)
      char *string;
      int *sindex;
+     int xflags;
 {
-  return (extract_delimited_string (string, sindex, "$(", "(", ")", 0));
+  if (string[*sindex] == '(')  /*)*/
+    return (extract_delimited_string (string, sindex, "$(", "(", ")", xflags|SX_COMMAND)); /*)*/
+  else
+    {
+      xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0);
+      return (xparse_dolparen (string, string+*sindex, sindex, xflags));
+    }
 }
 
 /* Extract the $[ construct in STRING, and return a new string. (])
@@ -927,12 +1032,25 @@ extract_process_subst (string, starter, sindex)
 #endif /* PROCESS_SUBSTITUTION */
 
 #if defined (ARRAY_VARS)
+/* This can be fooled by unquoted right parens in the passed string. If
+   each caller verifies that the last character in STRING is a right paren,
+   we don't even need to call extract_delimited_string. */
 char *
 extract_array_assignment_list (string, sindex)
      char *string;
      int *sindex;
 {
-  return (extract_delimited_string (string, sindex, "(", (char *)NULL, ")", 0));
+  int slen;
+  char *ret;
+
+  slen = strlen (string);      /* ( */
+  if (string[slen - 1] == ')')
+   {
+      ret = substring (string, *sindex, slen - 1);
+      *sindex = slen - 1;
+      return ret;
+    }
+  return 0;  
 }
 #endif
 
@@ -954,7 +1072,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
   int i, c, si;
   size_t slen;
   char *t, *result;
-  int pass_character, nesting_level;
+  int pass_character, nesting_level, in_comment;
   int len_closer, len_opener, len_alt_opener;
   DECLARE_MBSTATE;
 
@@ -963,7 +1081,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
   len_alt_opener = STRLEN (alt_opener);
   len_closer = STRLEN (closer);
 
-  pass_character = 0;
+  pass_character = in_comment = 0;
 
   nesting_level = 1;
   i = *sindex;
@@ -975,6 +1093,14 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
       if (c == 0)
        break;
 
+      if (in_comment)
+       {
+         if (c == '\n')
+           in_comment = 0;
+         ADVANCE_CHAR (string, slen, i);
+         continue;
+       }
+
       if (pass_character)      /* previous char was backslash */
        {
          pass_character = 0;
@@ -982,6 +1108,15 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
          continue;
        }
 
+      /* Not exactly right yet; should handle shell metacharacters and
+        multibyte characters, too. */
+      if ((flags & SX_COMMAND) && c == '#' && (i == 0 || string[i - 1] == '\n' || shellblank (string[i - 1])))
+       {
+          in_comment = 1;
+          ADVANCE_CHAR (string, slen, i);
+          continue;
+       }
+        
       if (c == CTLESC || c == '\\')
        {
          pass_character++;
@@ -993,7 +1128,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
       if (STREQN (string + i, opener, len_opener))
        {
          si = i + len_opener;
-         t = extract_delimited_string (string, &si, opener, alt_opener, closer, flags|EX_NOALLOC);
+         t = extract_delimited_string (string, &si, opener, alt_opener, closer, flags|SX_NOALLOC);
          i = si + 1;
          continue;
        }
@@ -1002,7 +1137,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
       if (len_alt_opener && STREQN (string + i, alt_opener, len_alt_opener))
        {
          si = i + len_alt_opener;
-         t = extract_delimited_string (string, &si, alt_opener, alt_opener, closer, flags|EX_NOALLOC);
+         t = extract_delimited_string (string, &si, alt_opener, alt_opener, closer, flags|SX_NOALLOC);
          i = si + 1;
          continue;
        }
@@ -1021,7 +1156,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
       if (c == '`')
        {
          si = i + 1;
-         t = string_extract (string, &si, "`", flags|EX_NOALLOC);
+         t = string_extract (string, &si, "`", flags|SX_NOALLOC);
          i = si + 1;
          continue;
        }
@@ -1055,7 +1190,7 @@ extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
     }
 
   si = i - *sindex - len_closer + 1;
-  if (flags & EX_NOALLOC)
+  if (flags & SX_NOALLOC)
     result = (char *)NULL;
   else    
     {
@@ -1130,7 +1265,7 @@ extract_dollar_brace_string (string, sindex, quoted, flags)
       if (c == '`')
        {
          si = i + 1;
-         t = string_extract (string, &si, "`", flags|EX_NOALLOC);
+         t = string_extract (string, &si, "`", flags|SX_NOALLOC);
          i = si + 1;
          continue;
        }
@@ -1140,7 +1275,7 @@ extract_dollar_brace_string (string, sindex, quoted, flags)
       if (string[i] == '$' && string[i+1] == LPAREN)
        {
          si = i + 2;
-         t = extract_delimited_string (string, &si, "$(", "(", ")", flags|EX_NOALLOC); /*)*/
+         t = extract_command_subst (string, &si, flags|SX_NOALLOC);
          i = si + 1;
          continue;
        }
@@ -1164,7 +1299,7 @@ extract_dollar_brace_string (string, sindex, quoted, flags)
     {
       if (no_longjmp_on_fatal_error == 0)
        {                       /* { */
-         report_error ("bad substitution: no closing `%s' in %s", "}", string);
+         report_error (_("bad substitution: no closing `%s' in %s"), "}", string);
          last_command_exit_value = EXECUTION_FAILURE;
          exp_jump_to_top_level (DISCARD);
        }
@@ -1175,7 +1310,7 @@ extract_dollar_brace_string (string, sindex, quoted, flags)
        }
     }
 
-  result = (flags & EX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
+  result = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
   *sindex = i;
 
   return (result);
@@ -1237,6 +1372,95 @@ unquote_bang (string)
 }
 #endif
 
+#define CQ_RETURN(x) do { no_longjmp_on_fatal_error = 0; return (x); } while (0)
+
+/* Skip characters in STRING until we find a character in DELIMS, and return
+   the index of that character.  START is the index into string at which we
+   begin.  This is similar in spirit to strpbrk, but it returns an index into
+   STRING and takes a starting index.  This little piece of code knows quite
+   a lot of shell syntax.  It's very similar to skip_double_quoted and other
+   functions of that ilk. */
+int
+skip_to_delim (string, start, delims, flags)
+     char *string;
+     int start;
+     char *delims;
+     int flags;
+{
+  int i, pass_next, backq, si, c, invert;
+  size_t slen;
+  char *temp;
+  DECLARE_MBSTATE;
+
+  slen = strlen (string + start) + start;
+  if (flags & SD_NOJMP)
+    no_longjmp_on_fatal_error = 1;
+  invert = (flags & SD_INVERT);
+
+  i = start;
+  pass_next = backq = 0;
+  while (c = string[i])
+    {
+      if (pass_next)
+       {
+         pass_next = 0;
+         if (c == 0)
+           CQ_RETURN(i);
+         ADVANCE_CHAR (string, slen, i);
+         continue;
+       }
+      else if (c == '\\')
+       {
+         pass_next = 1;
+         i++;
+         continue;
+       }
+      else if (backq)
+       {
+         if (c == '`')
+           backq = 0;
+         ADVANCE_CHAR (string, slen, i);
+         continue;
+       }
+      else if (c == '`')
+       {
+         backq = 1;
+         i++;
+         continue;
+       }
+      else if (invert == 0 && member (c, delims))
+       break;
+      else if (c == '\'' || c == '"')
+       {
+         i = (c == '\'') ? skip_single_quoted (string, slen, ++i)
+                         : skip_double_quoted (string, slen, ++i);
+         /* no increment, the skip functions increment past the closing quote. */
+       }
+      else if (c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE))
+       {
+         si = i + 2;
+         if (string[si] == '\0')
+           CQ_RETURN(si);
+
+         if (string[i+1] == LPAREN)
+           temp = extract_delimited_string (string, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */
+         else
+           temp = extract_dollar_brace_string (string, &si, 0, SX_NOALLOC);
+         i = si;
+         if (string[i] == '\0')        /* don't increment i past EOS in loop */
+           break;
+         i++;
+         continue;
+       }
+      else if (invert && (member (c, delims) == 0))
+       break;
+      else
+       ADVANCE_CHAR (string, slen, i);
+    }
+
+  CQ_RETURN(i);
+}
+
 #if defined (READLINE)
 /* Return 1 if the portion of STRING ending at EINDEX is quoted (there is
    an unclosed quoted string), or if the character at EINDEX is quoted
@@ -1246,8 +1470,6 @@ unquote_bang (string)
    recognizes need to be the same as the contents of
    rl_completer_quote_characters. */
 
-#define CQ_RETURN(x) do { no_longjmp_on_fatal_error = 0; return (x); } while (0)
-
 int
 char_is_quoted (string, eindex)
      char *string;
@@ -1340,87 +1562,6 @@ unclosed_pair (string, eindex, openstr)
   return (openc);
 }
 
-/* Skip characters in STRING until we find a character in DELIMS, and return
-   the index of that character.  START is the index into string at which we
-   begin.  This is similar in spirit to strpbrk, but it returns an index into
-   STRING and takes a starting index.  This little piece of code knows quite
-   a lot of shell syntax.  It's very similar to skip_double_quoted and other
-   functions of that ilk. */
-int
-skip_to_delim (string, start, delims)
-     char *string;
-     int start;
-     char *delims;
-{
-  int i, pass_next, backq, si, c;
-  size_t slen;
-  char *temp;
-  DECLARE_MBSTATE;
-
-  slen = strlen (string + start) + start;
-  no_longjmp_on_fatal_error = 1;
-  i = start;
-  pass_next = backq = 0;
-  while (c = string[i])
-    {
-      if (pass_next)
-       {
-         pass_next = 0;
-         if (c == 0)
-           CQ_RETURN(i);
-         ADVANCE_CHAR (string, slen, i);
-         continue;
-       }
-      else if (c == '\\')
-       {
-         pass_next = 1;
-         i++;
-         continue;
-       }
-      else if (backq)
-       {
-         if (c == '`')
-           backq = 0;
-         ADVANCE_CHAR (string, slen, i);
-         continue;
-       }
-      else if (c == '`')
-       {
-         backq = 1;
-         i++;
-         continue;
-       }
-      else if (c == '\'' || c == '"')
-       {
-         i = (c == '\'') ? skip_single_quoted (string, slen, ++i)
-                         : skip_double_quoted (string, slen, ++i);
-         /* no increment, the skip functions increment past the closing quote. */
-       }
-      else if (c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE))
-       {
-         si = i + 2;
-         if (string[si] == '\0')
-           CQ_RETURN(si);
-
-         if (string[i+1] == LPAREN)
-           temp = extract_delimited_string (string, &si, "$(", "(", ")", EX_NOALLOC); /* ) */
-         else
-           temp = extract_dollar_brace_string (string, &si, 0, EX_NOALLOC);
-         i = si;
-         if (string[i] == '\0')        /* don't increment i past EOS in loop */
-           break;
-         i++;
-         continue;
-       }
-      else if (member (c, delims))
-       break;
-      else
-       ADVANCE_CHAR (string, slen, i);
-    }
-
-  CQ_RETURN(i);
-}
-
 /* Split STRING (length SLEN) at DELIMS, and return a WORD_LIST with the
    individual words.  If DELIMS is NULL, the current value of $IFS is used
    to split the string, and the function follows the shell field splitting
@@ -1456,11 +1597,37 @@ split_at_delims (string, slen, delims, sentinel, nwp, cwp)
   d2 = 0;
   if (delims)
     {
-      d2 = (char *)xmalloc (strlen (delims) + 1);
-      for (i = ts = 0; delims[i]; i++)
+      size_t slength;
+#if defined (HANDLE_MULTIBYTE)
+      size_t mblength = 1;
+#endif
+      DECLARE_MBSTATE;
+
+      slength = strlen (delims);
+      d2 = (char *)xmalloc (slength + 1);
+      i = ts = 0;
+      while (delims[i])
        {
-         if (whitespace(delims[i]) == 0)
+#if defined (HANDLE_MULTIBYTE)
+         mbstate_t state_bak;
+         state_bak = state;
+         mblength = MBRLEN (delims + i, slength, &state);
+         if (MB_INVALIDCH (mblength))
+           state = state_bak;
+         else if (mblength > 1)
+           {
+             memcpy (d2 + ts, delims + i, mblength);
+             ts += mblength;
+             i += mblength;
+             slength -= mblength;
+             continue;
+           }
+#endif
+         if (whitespace (delims[i]) == 0)
            d2[ts++] = delims[i];
+
+         i++;
+         slength--;
        }
       d2[ts] = '\0';
     }
@@ -1479,7 +1646,7 @@ split_at_delims (string, slen, delims, sentinel, nwp, cwp)
   cw = -1;
   while (1)
     {
-      te = skip_to_delim (string, ts, d);
+      te = skip_to_delim (string, ts, d, SD_NOJMP);
 
       /* If we have a non-whitespace delimiter character, use it to make a
         separate field.  This is just about what $IFS splitting does and
@@ -1645,6 +1812,42 @@ string_list (list)
   return (string_list_internal (list, " "));
 }
 
+/* An external interface that can be used by the rest of the shell to
+   obtain a string containing the first character in $IFS.  Handles all
+   the multibyte complications.  If LENP is non-null, it is set to the
+   length of the returned string. */
+char *
+ifs_firstchar (lenp)
+     int *lenp;
+{
+  char *ret;
+  int len;
+
+  ret = xmalloc (MB_LEN_MAX + 1);
+#if defined (HANDLE_MULTIBYTE)
+  if (ifs_firstc_len == 1)
+    {
+      ret[0] = ifs_firstc[0];
+      ret[1] = '\0';
+      len = ret[0] ? 1 : 0;
+    }
+  else
+    {
+      memcpy (ret, ifs_firstc, ifs_firstc_len);
+      ret[len = ifs_firstc_len] = '\0';
+    }
+#else
+  ret[0] = ifs_firstc;
+  ret[1] = '\0';
+  len = ret[0] ? 0 : 1;
+#endif
+
+  if (lenp)
+    *lenp = len;
+
+  return ret;
+}
+
 /* Return a single string of all the words present in LIST, obeying the
    quoting rules for "$*", to wit: (P1003.2, draft 11, 3.5.2) "If the
    expansion [of $*] appears within a double quoted string, it expands
@@ -1654,12 +1857,41 @@ char *
 string_list_dollar_star (list)
      WORD_LIST *list;
 {
+  char *ret;
+#if defined (HANDLE_MULTIBYTE)
+#  if defined (__GNUC__)
+  char sep[MB_CUR_MAX + 1];
+#  else
+  char *sep = 0;
+#  endif
+#else
   char sep[2];
+#endif
 
+#if defined (HANDLE_MULTIBYTE)
+#  if !defined (__GNUC__)
+  sep = (char *)xmalloc (MB_CUR_MAX + 1);
+#  endif /* !__GNUC__ */
+  if (ifs_firstc_len == 1)
+    {
+      sep[0] = ifs_firstc[0];
+      sep[1] = '\0';
+    }
+  else
+    {
+      memcpy (sep, ifs_firstc, ifs_firstc_len);
+      sep[ifs_firstc_len] = '\0';
+    }
+#else
   sep[0] = ifs_firstc;
   sep[1] = '\0';
+#endif
 
-  return (string_list_internal (list, sep));
+  ret = string_list_internal (list, sep);
+#if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
+  free (sep);
+#endif
+  return ret;
 }
 
 /* Turn $@ into a string.  If (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
@@ -1676,19 +1908,112 @@ string_list_dollar_at (list, quoted)
      WORD_LIST *list;
      int quoted;
 {
-  char *ifs, sep[2];
+  char *ifs, *ret;
+#if defined (HANDLE_MULTIBYTE)
+#  if defined (__GNUC__)
+  char sep[MB_CUR_MAX + 1];
+#  else
+  char *sep = 0;
+#  endif /* !__GNUC__ */
+#else
+  char sep[2];
+#endif
   WORD_LIST *tlist;
 
   /* XXX this could just be ifs = ifs_value; */
   ifs = ifs_var ? value_cell (ifs_var) : (char *)0;
 
+#if defined (HANDLE_MULTIBYTE)
+#  if !defined (__GNUC__)
+  sep = (char *)xmalloc (MB_CUR_MAX + 1);
+#  endif /* !__GNUC__ */
+  if (ifs && *ifs)
+    {
+      if (ifs_firstc_len == 1)
+       {
+         sep[0] = ifs_firstc[0];
+         sep[1] = '\0';
+       }
+      else
+       {
+         memcpy (sep, ifs_firstc, ifs_firstc_len);
+         sep[ifs_firstc_len] = '\0';
+       }
+    }
+  else
+    {
+      sep[0] = ' ';
+      sep[1] = '\0';
+    }
+#else
   sep[0] = (ifs == 0 || *ifs == 0) ? ' ' : *ifs;
   sep[1] = '\0';
+#endif
 
+  /* XXX -- why call quote_list if ifs == 0?  we can get away without doing
+     it now that quote_escapes quotes spaces */
+#if 0
   tlist = ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (ifs && *ifs == 0))
+#else
+  tlist = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
+#endif
                ? quote_list (list)
                : list_quote_escapes (list);
-  return (string_list_internal (tlist, sep));
+
+  ret = string_list_internal (tlist, sep);
+#if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
+  free (sep);
+#endif
+  return ret;
+}
+
+/* Turn the positional paramters into a string, understanding quoting and
+   the various subtleties of using the first character of $IFS as the
+   separator.  Calls string_list_dollar_at, string_list_dollar_star, and
+   string_list as appropriate. */
+char *
+string_list_pos_params (pchar, list, quoted)
+     int pchar;
+     WORD_LIST *list;
+     int quoted;
+{
+  char *ret;
+  WORD_LIST *tlist;
+
+  if (pchar == '*' && (quoted & Q_DOUBLE_QUOTES))
+    {
+      tlist = quote_list (list);
+      word_list_remove_quoted_nulls (tlist);
+      ret = string_list_dollar_star (tlist);
+    }
+  else if (pchar == '*' && (quoted & Q_HERE_DOCUMENT))
+    {
+      tlist = quote_list (list);
+      word_list_remove_quoted_nulls (tlist);
+      ret = string_list (tlist);
+    }
+  else if (pchar == '*')
+    {
+      /* Even when unquoted, string_list_dollar_star does the right thing
+        making sure that the first character of $IFS is used as the
+        separator. */
+      ret = string_list_dollar_star (list);
+    }
+  else if (pchar == '@' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
+    /* We use string_list_dollar_at, but only if the string is quoted, since
+       that quotes the escapes if it's not, which we don't want.  We could
+       use string_list (the old code did), but that doesn't do the right
+       thing if the first character of $IFS is not a space.  We use
+       string_list_dollar_star if the string is unquoted so we make sure that
+       the elements of $@ are separated by the first character of $IFS for
+       later splitting. */
+    ret = string_list_dollar_at (list, quoted);
+  else if (pchar == '@')
+    ret = string_list_dollar_star (list);
+  else
+    ret = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (list) : list);
+
+  return ret;
 }
 
 /* Return the list of words present in STRING.  Separate the string into
@@ -1731,7 +2056,8 @@ list_string (string, separators, quoted)
   WORD_LIST *result;
   WORD_DESC *t;
   char *current_word, *s;
-  int sindex, sh_style_split, whitesep;
+  int sindex, sh_style_split, whitesep, xflags;
+  size_t slen;
 
   if (!string || !*string)
     return ((WORD_LIST *)NULL);
@@ -1740,7 +2066,13 @@ list_string (string, separators, quoted)
                                 separators[1] == '\t' &&
                                 separators[2] == '\n' &&
                                 separators[3] == '\0';
+  for (xflags = 0, s = ifs_value; s && *s; s++)
+    {
+      if (*s == CTLESC) xflags |= SX_NOCTLESC;
+      else if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
+    }
 
+  slen = 0;
   /* Remove sequences of whitespace at the beginning of STRING, as
      long as those characters appear in IFS.  Do not do this if
      STRING is quoted or if there are no separator characters. */
@@ -1759,9 +2091,12 @@ list_string (string, separators, quoted)
        extract a word, stopping at a separator
        skip sequences of spc, tab, or nl as long as they are separators
      This obeys the field splitting rules in Posix.2. */
+  slen = (MB_CUR_MAX > 1) ? strlen (string) : 1;
   for (result = (WORD_LIST *)NULL, sindex = 0; string[sindex]; )
     {
-      current_word = string_extract_verbatim (string, &sindex, separators);
+      /* Don't need string length in ADVANCE_CHAR or string_extract_verbatim
+        unless multibyte chars are possible. */
+      current_word = string_extract_verbatim (string, slen, &sindex, separators, xflags);
       if (current_word == 0)
        break;
 
@@ -1771,10 +2106,9 @@ list_string (string, separators, quoted)
         below. */
       if (QUOTED_NULL (current_word))
        {
-         t = make_bare_word ("");
-         t->flags |= W_QUOTED;
-         free (t->word);
+         t = alloc_word_desc ();
          t->word = make_quoted_char ('\0');
+         t->flags |= W_QUOTED|W_HASQUOTEDNULL;
          result = make_word_list (t, result);
        }
       else if (current_word[0] != '\0')
@@ -1783,6 +2117,7 @@ list_string (string, separators, quoted)
             perform quoted null character removal on the current word. */
          remove_quoted_nulls (current_word);
          result = add_string_to_list (current_word, result);
+         result->word->flags &= ~W_HASQUOTEDNULL;      /* just to be sure */
          if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
            result->word->flags |= W_QUOTED;
        }
@@ -1791,10 +2126,9 @@ list_string (string, separators, quoted)
         Bourne shell style, then add a quoted null argument. */
       else if (!sh_style_split && !spctabnl (string[sindex]))
        {
-         t = make_bare_word ("");
-         t->flags |= W_QUOTED;
-         free (t->word);
+         t = alloc_word_desc ();
          t->word = make_quoted_char ('\0');
+         t->flags |= W_QUOTED|W_HASQUOTEDNULL;
          result = make_word_list (t, result);
        }
 
@@ -1805,7 +2139,10 @@ list_string (string, separators, quoted)
 
       /* Move past the current separator character. */
       if (string[sindex])
-       sindex++;
+       {
+         DECLARE_MBSTATE;
+         ADVANCE_CHAR (string, slen, sindex);
+       }
 
       /* Now skip sequences of space, tab, or newline characters if they are
         in the list of separators. */
@@ -1817,7 +2154,13 @@ list_string (string, separators, quoted)
         field delimiter, not a separate delimiter that would result in an
         empty field.  Look at POSIX.2, 3.6.5, (3)(b). */
       if (string[sindex] && whitesep && issep (string[sindex]) && !spctabnl (string[sindex]))
-       sindex++;
+       {
+         sindex++;
+         /* An IFS character that is not IFS white space, along with any
+            adjacent IFS white space, shall delimit a field. (SUSv3) */
+         while (string[sindex] && spctabnl (string[sindex]) && isifs (string[sindex]))
+           sindex++;
+       }
     }
   return (REVERSE_LIST (result, WORD_LIST *));
 }
@@ -1835,17 +2178,24 @@ get_word_from_string (stringp, separators, endptr)
 {
   register char *s;
   char *current_word;
-  int sindex, sh_style_split, whitesep;
+  int sindex, sh_style_split, whitesep, xflags;
+  size_t slen;
 
   if (!stringp || !*stringp || !**stringp)
     return ((char *)NULL);
 
-  s = *stringp;
-
   sh_style_split = separators && separators[0] == ' ' &&
                                 separators[1] == '\t' &&
                                 separators[2] == '\n' &&
                                 separators[3] == '\0';
+  for (xflags = 0, s = ifs_value; s && *s; s++)
+    {
+      if (*s == CTLESC) xflags |= SX_NOCTLESC;
+      if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
+    }
+
+  s = *stringp;
+  slen = 0;
 
   /* Remove sequences of whitespace at the beginning of STRING, as
      long as those characters appear in IFS. */
@@ -1870,7 +2220,10 @@ get_word_from_string (stringp, separators, endptr)
 
      This obeys the field splitting rules in Posix.2. */
   sindex = 0;
-  current_word = string_extract_verbatim (s, &sindex, separators);
+  /* Don't need string length in ADVANCE_CHAR or string_extract_verbatim
+     unless multibyte chars are possible. */
+  slen = (MB_CUR_MAX > 1) ? strlen (s) : 1;
+  current_word = string_extract_verbatim (s, slen, &sindex, separators, xflags);
 
   /* Set ENDPTR to the first character after the end of the word. */
   if (endptr)
@@ -1881,7 +2234,10 @@ get_word_from_string (stringp, separators, endptr)
 
   /* Move past the current separator character. */
   if (s[sindex])
-    sindex++;
+    {
+      DECLARE_MBSTATE;
+      ADVANCE_CHAR (s, slen, sindex);
+    }
 
   /* Now skip sequences of space, tab, or newline characters if they are
      in the list of separators. */
@@ -1893,7 +2249,13 @@ get_word_from_string (stringp, separators, endptr)
      delimiter, not a separate delimiter that would result in an empty field.
      Look at POSIX.2, 3.6.5, (3)(b). */
   if (s[sindex] && whitesep && isifs (s[sindex]) && !spctabnl (s[sindex]))
-    sindex++;
+    {
+      sindex++;
+      /* An IFS character that is not IFS white space, along with any adjacent
+        IFS white space, shall delimit a field. */
+      while (s[sindex] && spctabnl (s[sindex]) && isifs (s[sindex]))
+       sindex++;
+    }
 
   /* Update STRING to point to the next field. */
   *stringp = s + sindex;
@@ -1981,25 +2343,60 @@ list_string_with_quotes (string)
 /*                                                     */
 /********************************************************/
 
+#if defined (ARRAY_VARS)
+static SHELL_VAR *
+do_compound_assignment (name, value, flags)
+     char *name, *value;
+     int flags;
+{
+  SHELL_VAR *v;
+  int mklocal, mkassoc;
+  WORD_LIST *list;
+
+  mklocal = flags & ASS_MKLOCAL;
+  mkassoc = flags & ASS_MKASSOC;
+
+  if (mklocal && variable_context)
+    {
+      v = find_variable (name);
+      list = expand_compound_array_assignment (v, value, flags);
+      if (mkassoc)
+       v = make_local_assoc_variable (name);
+      else if (v == 0 || (array_p (v) == 0 && assoc_p (v) == 0) || v->context != variable_context)
+        v = make_local_array_variable (name);
+      assign_compound_array_list (v, list, flags);
+    }
+  else
+    v = assign_array_from_string (name, value, flags);
+
+  return (v);
+}
+#endif
+
 /* Given STRING, an assignment string, get the value of the right side
    of the `=', and bind it to the left side.  If EXPAND is true, then
    perform parameter expansion, command substitution, and arithmetic
    expansion on the right-hand side.  Perform tilde expansion in any
    case.  Do not perform word splitting on the result of expansion. */
 static int
-do_assignment_internal (string, expand)
-     const char *string;
+do_assignment_internal (word, expand)
+     const WORD_DESC *word;
      int expand;
 {
-  int offset;
+  int offset, tlen, appendop, assign_list, aflags, retval;
   char *name, *value;
   SHELL_VAR *entry;
 #if defined (ARRAY_VARS)
   char *t;
   int ni;
 #endif
-  int assign_list = 0;
+  const char *string;
 
+  if (word == 0 || word->word == 0)
+    return 0;
+
+  appendop = assign_list = aflags = 0;
+  string = word->word;
   offset = assignment (string, 0);
   name = savestring (string);
   value = (char *)NULL;
@@ -2008,28 +2405,27 @@ do_assignment_internal (string, expand)
     {
       char *temp;
 
-      name[offset] = 0;
+      if (name[offset - 1] == '+')
+       {
+         appendop = 1;
+         name[offset - 1] = '\0';
+       }
+
+      name[offset] = 0;                /* might need this set later */
       temp = name + offset + 1;
+      tlen = STRLEN (temp);
 
 #if defined (ARRAY_VARS)
-      if (expand && temp[0] == LPAREN && xstrchr (temp, RPAREN))
+      if (expand && (word->flags & W_COMPASSIGN))
        {
          assign_list = ni = 1;
-         value = extract_delimited_string (temp, &ni, "(", (char *)NULL, ")", 0);
+         value = extract_array_assignment_list (temp, &ni);
        }
       else
 #endif
 
-      /* Perform tilde expansion. */
       if (expand && temp[0])
-       {
-         temp = (xstrchr (temp, '~') && unquoted_member ('~', temp))
-                       ? bash_tilde_expand (temp, 1)
-                       : savestring (temp);
-
-         value = expand_string_if_necessary (temp, 0, expand_string_unsplit);
-         free (temp);
-       }
+       value = expand_string_if_necessary (temp, 0, expand_string_assignment);
       else
        value = savestring (temp);
     }
@@ -2041,10 +2437,19 @@ do_assignment_internal (string, expand)
     }
 
   if (echo_command_at_execute)
-     xtrace_print_assignment (name, value, assign_list, 1);
+    {
+      if (appendop)
+       name[offset - 1] = '+';
+      xtrace_print_assignment (name, value, assign_list, 1);
+      if (appendop)
+       name[offset - 1] = '\0';
+    }
 
 #define ASSIGN_RETURN(r)       do { FREE (value); free (name); return (r); } while (0)
 
+  if (appendop)
+    aflags |= ASS_APPEND;
+
 #if defined (ARRAY_VARS)
   if (t = xstrchr (name, '[')) /*]*/
     {
@@ -2053,42 +2458,82 @@ do_assignment_internal (string, expand)
          report_error (_("%s: cannot assign list to array member"), name);
          ASSIGN_RETURN (0);
        }
-      entry = assign_array_element (name, value);
+      entry = assign_array_element (name, value, aflags);
       if (entry == 0)
        ASSIGN_RETURN (0);
     }
   else if (assign_list)
-    entry = assign_array_from_string (name, value);
+    {
+      if (word->flags & W_ASSIGNARG)
+       aflags |= ASS_MKLOCAL;
+      if (word->flags & W_ASSIGNASSOC)
+       aflags |= ASS_MKASSOC;
+      entry = do_compound_assignment (name, value, aflags);
+    }
   else
 #endif /* ARRAY_VARS */
-  entry = bind_variable (name, value);
+  entry = bind_variable (name, value, aflags);
 
   stupidly_hack_special_variables (name);
 
+#if 1
+  /* Return 1 if the assignment seems to have been performed correctly. */
+  if (entry == 0 || readonly_p (entry))
+    retval = 0;                /* assignment failure */
+  else if (noassign_p (entry))
+    {
+      last_command_exit_value = EXECUTION_FAILURE;
+      retval = 1;      /* error status, but not assignment failure */
+    }
+  else
+    retval = 1;
+
+  if (entry && retval != 0 && noassign_p (entry) == 0)
+    VUNSETATTR (entry, att_invisible);
+
+  ASSIGN_RETURN (retval);
+#else
   if (entry)
     VUNSETATTR (entry, att_invisible);
 
-  /* Return 1 if the assignment seems to have been performed correctly. */
   ASSIGN_RETURN (entry ? ((readonly_p (entry) == 0) && noassign_p (entry) == 0) : 0);
+#endif
 }
 
 /* Perform the assignment statement in STRING, and expand the
-   right side by doing command and parameter expansion. */
+   right side by doing tilde, command and parameter expansion. */
 int
 do_assignment (string)
-     const char *string;
+     char *string;
+{
+  WORD_DESC td;
+
+  td.flags = W_ASSIGNMENT;
+  td.word = string;
+
+  return do_assignment_internal (&td, 1);
+}
+
+int
+do_word_assignment (word)
+     WORD_DESC *word;
 {
-  return do_assignment_internal (string, 1);
+  return do_assignment_internal (word, 1);
 }
 
 /* Given STRING, an assignment string, get the value of the right side
-   of the `=', and bind it to the left side.  Do not do command and
-   parameter substitution on the right hand side. */
+   of the `=', and bind it to the left side.  Do not perform any word
+   expansions on the right hand side. */
 int
 do_assignment_no_expand (string)
-     const char *string;
+     char *string;
 {
-  return do_assignment_internal (string, 0);
+  WORD_DESC td;
+
+  td.flags = W_ASSIGNMENT;
+  td.word = string;
+
+  return (do_assignment_internal (&td, 0));
 }
 
 /***************************************************
@@ -2185,6 +2630,12 @@ pos_params (string, start, end, quoted)
   if (save == 0)
     return ((char *)NULL);
 
+  if (start == 0)              /* handle ${@:0[:x]} specially */
+    {
+      t = make_word_list (make_word (dollar_vars[0]), params);
+      save = params = t;
+    }
+
   for (i = 1; params && i < start; i++)
     params = params->next;
   if (params == 0)
@@ -2196,21 +2647,9 @@ pos_params (string, start, end, quoted)
     }
 
   t->next = (WORD_LIST *)NULL;
-  if (string[0] == '*')
-#if 0
-    ret = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? string_list_dollar_star (quote_list (h)) : string_list (h);
-#else
-    {
-      if (quoted & Q_DOUBLE_QUOTES)
-       ret = string_list_dollar_star (quote_list (h));
-      else if (quoted & Q_HERE_DOCUMENT)
-       ret = string_list (quote_list (h));
-      else
-       ret = string_list (h);
-    }
-#endif
-  else
-    ret = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (h) : h);
+
+  ret = string_list_pos_params (string[0], h, quoted);
+
   if (t != params)
     t->next = params;
 
@@ -2225,9 +2664,9 @@ pos_params (string, start, end, quoted)
 /******************************************************************/
 
 #if defined (PROCESS_SUBSTITUTION)
-#define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC)
+#define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC || s == '~')
 #else
-#define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC)
+#define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC || s == '~')
 #endif
 
 /* If there are any characters in STRING that require full expansion,
@@ -2245,7 +2684,8 @@ expand_string_if_necessary (string, quoted, func)
   char *ret;
   DECLARE_MBSTATE;
 
-  slen = strlen (string);
+  /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */
+  slen = (MB_CUR_MAX > 1) ? strlen (string) : 0;
   i = saw_quote = 0;
   while (string[i])
     {
@@ -2315,6 +2755,22 @@ expand_string_unsplit_to_string (string, quoted)
   return (expand_string_to_string_internal (string, quoted, expand_string_unsplit));
 }
 
+char *
+expand_assignment_string_to_string (string, quoted)
+     char *string;
+     int quoted;
+{
+  return (expand_string_to_string_internal (string, quoted, expand_string_assignment));
+}
+
+char *
+expand_arith_string (string, quoted)
+     char *string;
+     int quoted;
+{
+  return (expand_string_if_necessary (string, quoted, expand_string));
+}
+
 #if defined (COND_COMMAND)
 /* Just remove backslashes in STRING.  Returns a new string. */
 char *
@@ -2338,11 +2794,12 @@ remove_backslashes (string)
 
 /* This needs better error handling. */
 /* Expand W for use as an argument to a unary or binary operator in a
-   [[...]] expression.  If SPECIAL is nonzero, this is the rhs argument
+   [[...]] expression.  If SPECIAL is 1, this is the rhs argument
    to the != or == operator, and should be treated as a pattern.  In
-   this case, we quote the string specially for the globbing code.  The
-   caller is responsible for removing the backslashes if the unquoted
-   words is needed later. */   
+   this case, we quote the string specially for the globbing code.  If
+   SPECIAL is 2, this is an rhs argument for the =~ operator, and should
+   be quoted appropriately for regcomp/regexec.  The caller is responsible
+   for removing the backslashes if the unquoted word is needed later. */   
 char *
 cond_expand_word (w, special)
      WORD_DESC *w;
@@ -2350,17 +2807,11 @@ cond_expand_word (w, special)
 {
   char *r, *p;
   WORD_LIST *l;
+  int qflags;
 
   if (w->word == 0 || w->word[0] == '\0')
     return ((char *)NULL);
 
-  if (xstrchr (w->word, '~') && unquoted_member ('~', w->word))
-    {
-      p = bash_tilde_expand (w->word, 0);
-      free (w->word);
-      w->word = p;
-    }
-
   l = call_expand_word_internal (w, 0, 0, (int *)0, (int *)0);
   if (l)
     {
@@ -2371,8 +2822,11 @@ cond_expand_word (w, special)
        }
       else
        {
+         qflags = QGLOB_CVTNULL;
+         if (special == 2)
+           qflags |= QGLOB_REGEXP;
          p = string_list (l);
-         r = quote_string_for_globbing (p, QGLOB_CVTNULL);
+         r = quote_string_for_globbing (p, qflags);
          free (p);
        }
       dispose_words (l);
@@ -2454,7 +2908,43 @@ expand_string_unsplit (string, quoted)
   if (value)
     {
       if (value->word)
-       remove_quoted_nulls (value->word->word);
+       {
+         remove_quoted_nulls (value->word->word);
+         value->word->flags &= ~W_HASQUOTEDNULL;
+       }
+      dequote_list (value);
+    }
+  return (value);
+}
+
+/* Expand the rhs of an assignment statement */
+WORD_LIST *
+expand_string_assignment (string, quoted)
+     char *string;
+     int quoted;
+{
+  WORD_DESC td;
+  WORD_LIST *value;
+
+  if (string == 0 || *string == '\0')
+    return ((WORD_LIST *)NULL);
+
+  expand_no_split_dollar_star = 1;
+
+  td.flags = W_ASSIGNRHS;
+  td.word = savestring (string);
+  value = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
+  FREE (td.word);
+
+  expand_no_split_dollar_star = 0;
+
+  if (value)
+    {
+      if (value->word)
+       {
+         remove_quoted_nulls (value->word->word);
+         value->word->flags &= ~W_HASQUOTEDNULL;
+       }
       dequote_list (value);
     }
   return (value);
@@ -2466,9 +2956,10 @@ expand_string_unsplit (string, quoted)
    passed string when an error occurs.  Might want to trap other calls
    to jump_to_top_level here so we don't endlessly loop. */
 WORD_LIST *
-expand_prompt_string (string, quoted)
+expand_prompt_string (string, quoted, wflags)
      char *string;
      int quoted;
+     int wflags;
 {
   WORD_LIST *value;
   WORD_DESC td;
@@ -2476,7 +2967,7 @@ expand_prompt_string (string, quoted)
   if (string == 0 || *string == 0)
     return ((WORD_LIST *)NULL);
 
-  td.flags = 0;
+  td.flags = wflags;
   td.word = savestring (string);
 
   no_longjmp_on_fatal_error = 1;
@@ -2492,7 +2983,10 @@ expand_prompt_string (string, quoted)
   if (value)
     {
       if (value->word)
-       remove_quoted_nulls (value->word->word);
+       {
+         remove_quoted_nulls (value->word->word);
+         value->word->flags &= ~W_HASQUOTEDNULL;
+       }
       dequote_list (value);
     }
   return (value);
@@ -2576,7 +3070,14 @@ expand_string (string, quoted)
 
 /* Quote escape characters in string s, but no other characters.  This is
    used to protect CTLESC and CTLNUL in variable values from the rest of
-   the word expansion process after the variable is expanded. */
+   the word expansion process after the variable is expanded (word splitting
+   and filename generation).  If IFS is null, we quote spaces as well, just
+   in case we split on spaces later (in the case of unquoted $@, we will
+   eventually attempt to split the entire word on spaces).  Corresponding
+   code exists in dequote_escapes.  Even if we don't end up splitting on
+   spaces, quoting spaces is not a problem.  This should never be called on
+   a string that is quoted with single or double quotes or part of a here
+   document (effectively double-quoted). */
 char *
 quote_escapes (string)
      char *string;
@@ -2584,17 +3085,23 @@ quote_escapes (string)
   register char *s, *t;
   size_t slen;
   char *result, *send;
+  int quote_spaces, skip_ctlesc, skip_ctlnul;
   DECLARE_MBSTATE; 
 
   slen = strlen (string);
   send = string + slen;
 
+  quote_spaces = (ifs_value && *ifs_value == 0);
+
+  for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++)
+    skip_ctlesc |= *s == CTLESC, skip_ctlnul |= *s == CTLNUL;
+
   t = result = (char *)xmalloc ((slen * 2) + 1);
   s = string;
 
   while (*s)
     {
-      if (*s == CTLESC || *s == CTLNUL)
+      if ((skip_ctlesc == 0 && *s == CTLESC) || (skip_ctlnul == 0 && *s == CTLNUL) || (quote_spaces && *s == ' '))
        *t++ = CTLESC;
       COPY_CHAR_P (t, s, send);
     }
@@ -2629,13 +3136,14 @@ list_quote_escapes (list)
    characters.
 
    Also used by parts of the pattern substitution code. */
-static char *
+char *
 dequote_escapes (string)
      char *string;
 {
-  register char *s, *t;
+  register char *s, *t, *s1;
   size_t slen;
   char *result, *send;
+  int quote_spaces;
   DECLARE_MBSTATE;
 
   if (string == 0)
@@ -2645,14 +3153,16 @@ dequote_escapes (string)
   send = string + slen;
 
   t = result = (char *)xmalloc (slen + 1);
-  s = string;
 
   if (strchr (string, CTLESC) == 0)
-    return (strcpy (result, s));
+    return (strcpy (result, string));
 
+  quote_spaces = (ifs_value && *ifs_value == 0);
+
+  s = string;
   while (*s)
     {
-      if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL))
+      if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL || (quote_spaces && s[1] == ' ')))
        {
          s++;
          if (*s == '\0')
@@ -2664,7 +3174,9 @@ dequote_escapes (string)
   return result;
 }
 
-/* Return a new string with the quoted representation of character C. */
+/* Return a new string with the quoted representation of character C.
+   This turns "" into QUOTED_NULL, so the W_HASQUOTEDNULL flag needs to be
+   set in any resultant WORD_DESC where this value is the word. */
 static char *
 make_quoted_char (c)
      int c;
@@ -2686,7 +3198,9 @@ make_quoted_char (c)
   return (temp);
 }
 
-/* Quote STRING.  Return a new string. */
+/* Quote STRING, returning a new string.  This turns "" into QUOTED_NULL, so
+   the W_HASQUOTEDNULL flag needs to be set in any resultant WORD_DESC where
+   this value is the word. */
 char *
 quote_string (string)
      char *string;
@@ -2720,7 +3234,7 @@ quote_string (string)
   return (result);
 }
 
-/* De-quoted quoted characters in STRING. */
+/* De-quote quoted characters in STRING. */
 char *
 dequote_string (string)
      char *string;
@@ -2774,13 +3288,16 @@ quote_list (list)
     {
       t = w->word->word;
       w->word->word = quote_string (t);
-      free (t);
+      if (*t == 0)
+       w->word->flags |= W_HASQUOTEDNULL;      /* XXX - turn on W_HASQUOTEDNULL here? */
       w->word->flags |= W_QUOTED;
+      free (t);
     }
   return list;
 }
 
-static WORD_LIST *
+/* De-quote quoted characters in each word in LIST. */
+WORD_LIST *
 dequote_list (list)
      WORD_LIST *list;
 {
@@ -2790,6 +3307,8 @@ dequote_list (list)
   for (tlist = list; tlist; tlist = tlist->next)
     {
       s = dequote_string (tlist->word->word);
+      if (QUOTED_NULL (tlist->word->word))
+       tlist->word->flags &= ~W_HASQUOTEDNULL;
       free (tlist->word->word);
       tlist->word->word = s;
     }
@@ -2798,7 +3317,7 @@ dequote_list (list)
 
 /* Remove CTLESC protecting a CTLESC or CTLNUL in place.  Return the passed
    string. */
-static char *
+char *
 remove_quoted_escapes (string)
      char *string;
 {
@@ -2819,7 +3338,7 @@ remove_quoted_escapes (string)
    of how expand_word_internal works.  remove_quoted_nulls () turns
    STRING into an empty string iff it only consists of a quoted null,
    and removes all unquoted CTLNUL characters. */
-static char *
+char *
 remove_quoted_nulls (string)
      char *string;
 {
@@ -2871,7 +3390,10 @@ word_list_remove_quoted_nulls (list)
   register WORD_LIST *t;
 
   for (t = list; t; t = t->next)
-    remove_quoted_nulls (t->word->word);
+    {
+      remove_quoted_nulls (t->word->word);
+      t->word->flags &= ~W_HASQUOTEDNULL;
+    }
 }
 
 /* **************************************************************** */
@@ -2992,23 +3514,6 @@ remove_upattern (param, pattern, op)
 }
 
 #if defined (HANDLE_MULTIBYTE)
-
-#if !defined (HAVE_WCSDUP)
-static wchar_t *
-wcsdup (ws)
-     wchar_t *ws;
-{
-  wchar_t *ret;
-  size_t len;
-
-  len = wcslen (ws);
-  ret = xmalloc ((len + 1) * sizeof (wchar_t));
-  if (ret == 0)
-    return ret;
-  return (wcscpy (ret, ws));
-}
-#endif /* !HAVE_WCSDUP */
-
 static wchar_t *
 remove_wpattern (wparam, wstrlen, wpattern, op)
      wchar_t *wparam;
@@ -3016,9 +3521,8 @@ remove_wpattern (wparam, wstrlen, wpattern, op)
      wchar_t *wpattern;
      int op;
 {
-  wchar_t wc;
-  int n, n1;
-  wchar_t *ret;
+  wchar_t wc, *ret;
+  int n;
 
   switch (op)
     {
@@ -3113,7 +3617,7 @@ remove_pattern (param, pattern, op)
       free (wpattern);
 
       n = strlen (param);
-      xret = xmalloc (n + 1);
+      xret = (char *)xmalloc (n + 1);
       memset (&ps, '\0', sizeof (mbstate_t));
       n = wcsrtombs (xret, (const wchar_t **)&ret, n, &ps);
       xret[n] = '\0';          /* just to make sure */
@@ -3168,9 +3672,38 @@ match_upattern (string, pat, mtype, sp, ep)
      char **sp, **ep;
 {
   int c, len;
-  register char *p, *p1;
+  register char *p, *p1, *npat;
   char *end;
 
+  /* If the pattern doesn't match anywhere in the string, go ahead and
+     short-circuit right away.  A minor optimization, saves a bunch of
+     unnecessary calls to strmatch (up to N calls for a string of N
+     characters) if the match is unsuccessful.  To preserve the semantics
+     of the substring matches below, we make sure that the pattern has
+     `*' as first and last character, making a new pattern if necessary. */
+  /* XXX - check this later if I ever implement `**' with special meaning,
+     since this will potentially result in `**' at the beginning or end */
+  len = STRLEN (pat);
+  if (pat[0] != '*' || (pat[0] == '*' && pat[1] == '(' && extended_glob) || pat[len - 1] != '*')       /*)*/
+    {
+      p = npat = (char *)xmalloc (len + 3);
+      p1 = pat;
+      if (*p1 != '*' || (*p1 == '*' && p1[1] == '(' && extended_glob)) /*)*/
+       *p++ = '*';
+      while (*p1)
+       *p++ = *p1++;
+      if (p1[-1] != '*' || p[-2] == '\\')
+       *p++ = '*';
+      *p = '\0';
+    }
+  else
+    npat = pat;
+  c = strmatch (npat, string, FNMATCH_EXTFLAG);
+  if (npat != pat)
+    free (npat);
+  if (c == FNM_NOMATCH)
+    return (0);
+
   len = STRLEN (string);
   end = string + len;
 
@@ -3278,7 +3811,7 @@ match_wpattern (wstring, indices, wstrlen, wpat, mtype, sp, ep)
      int mtype;
      char **sp, **ep;
 {
-  wchar_t wc;
+  wchar_t wc, *wp, *nwpat, *wp1;
   int len;
 #if 0
   size_t n, n1;        /* Apple's gcc seems to miscompile this badly */
@@ -3286,6 +3819,35 @@ match_wpattern (wstring, indices, wstrlen, wpat, mtype, sp, ep)
   int n, n1;
 #endif
 
+  /* If the pattern doesn't match anywhere in the string, go ahead and
+     short-circuit right away.  A minor optimization, saves a bunch of
+     unnecessary calls to strmatch (up to N calls for a string of N
+     characters) if the match is unsuccessful.  To preserve the semantics
+     of the substring matches below, we make sure that the pattern has
+     `*' as first and last character, making a new pattern if necessary. */
+  /* XXX - check this later if I ever implement `**' with special meaning,
+     since this will potentially result in `**' at the beginning or end */
+  len = wcslen (wpat);
+  if (wpat[0] != L'*' || (wpat[0] == L'*' && wpat[1] == L'(' && extended_glob) || wpat[len - 1] != L'*')       /*)*/
+    {
+      wp = nwpat = (wchar_t *)xmalloc ((len + 3) * sizeof (wchar_t));
+      wp1 = wpat;
+      if (*wp1 != L'*' || (*wp1 == '*' && wp1[1] == '(' && extended_glob))     /*)*/
+       *wp++ = L'*';
+      while (*wp1 != L'\0')
+       *wp++ = *wp1++;
+      if (wp1[-1] != L'*' || wp1[-2] == L'\\')
+        *wp++ = L'*';
+      *wp = '\0';
+    }
+  else
+    nwpat = wpat;
+  len = wcsmatch (nwpat, wstring, FNMATCH_EXTFLAG);
+  if (nwpat != wpat)
+    free (nwpat);
+  if (len == FNM_NOMATCH)
+    return (0);
+
   switch (mtype)
     {
     case MATCH_ANY:
@@ -3414,10 +3976,9 @@ getpattern (value, quoted, expandpat)
 {
   char *pat, *tword;
   WORD_LIST *l;
+#if 0
   int i;
-
-  tword = xstrchr (value, '~') ? bash_tilde_expand (value, 0) : savestring (value);
-
+#endif
   /* There is a problem here:  how to handle single or double quotes in the
      pattern string when the whole expression is between double quotes?
      POSIX.2 says that enclosing double quotes do not cause the pattern to
@@ -3435,11 +3996,10 @@ getpattern (value, quoted, expandpat)
 
   /* expand_string_for_rhs () leaves WORD quoted and does not perform
      word splitting. */
-  l = *tword ? expand_string_for_rhs (tword,
+  l = *value ? expand_string_for_rhs (value,
                                      (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? Q_PATQUOTE : quoted,
                                      (int *)NULL, (int *)NULL)
             : (WORD_LIST *)0;
-  free (tword);
   pat = string_list (l);
   dispose_words (l);
   if (pat)
@@ -3480,22 +4040,15 @@ list_remove_pattern (list, pattern, patspec, itype, quoted)
   for (new = (WORD_LIST *)NULL, l = list; l; l = l->next)
     {
       tword = remove_pattern (l->word->word, pattern, patspec);
-      w = make_bare_word (tword);
-      FREE (tword);
+      w = alloc_word_desc ();
+      w->word = tword ? tword : savestring ("");
       new = make_word_list (w, new);
     }
 
   l = REVERSE_LIST (new, WORD_LIST *);
-  if (itype == '*')
-#if 0
-    tword = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? string_list_dollar_star (l) : string_list (l);
-#else
-    tword = (quoted & Q_DOUBLE_QUOTES) ? string_list_dollar_star (l) : string_list (l);
-#endif
-  else
-    tword = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (l) : l);
-
+  tword = string_list_pos_params (itype, l, quoted);
   dispose_words (l);
+
   return (tword);
 }
 
@@ -3518,13 +4071,15 @@ parameter_list_remove_pattern (itype, pattern, patspec, quoted)
 
 #if defined (ARRAY_VARS)
 static char *
-array_remove_pattern (a, pattern, patspec, varname, quoted)
-     ARRAY *a;
+array_remove_pattern (var, pattern, patspec, varname, quoted)
+     SHELL_VAR *var;
      char *pattern;
      int patspec;
      char *varname;    /* so we can figure out how it's indexed */
      int quoted;
 {
+  ARRAY *a;
+  HASH_TABLE *h;
   int itype;
   char *ret;
   WORD_LIST *list;
@@ -3534,7 +4089,10 @@ array_remove_pattern (a, pattern, patspec, varname, quoted)
   v = array_variable_part (varname, &ret, 0);
   itype = ret[0];
 
-  list = array_to_word_list (a);
+  a = (v && array_p (v)) ? array_cell (v) : 0;
+  h = (v && assoc_p (v)) ? assoc_cell (v) : 0;
+  
+  list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0);
   if (list == 0)
    return ((char *)NULL);
   ret = list_remove_pattern (list, pattern, patspec, itype, quoted);
@@ -3569,7 +4127,11 @@ parameter_brace_remove_pattern (varname, value, patstr, rtype, quoted)
   if (patspec == RP_LONG_LEFT || patspec == RP_LONG_RIGHT)
     patstr++;
 
-  pattern = getpattern (patstr, quoted, 1);
+  /* Need to pass getpattern newly-allocated memory in case of expansion --
+     the expansion code will free the passed string on an error. */
+  temp1 = savestring (patstr);
+  pattern = getpattern (temp1, quoted, 1);
+  free (temp1);
 
   temp1 = (char *)NULL;                /* shut up gcc */
   switch (vtype)
@@ -3581,14 +4143,16 @@ parameter_brace_remove_pattern (varname, value, patstr, rtype, quoted)
        FREE (val);
       if (temp1)
        {
-         val = quote_escapes (temp1);
+         val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
+                       ? quote_string (temp1)
+                       : quote_escapes (temp1);
          free (temp1);
          temp1 = val;
        }
       break;
 #if defined (ARRAY_VARS)
     case VT_ARRAYVAR:
-      temp1 = array_remove_pattern (array_cell (v), pattern, patspec, varname, quoted);
+      temp1 = array_remove_pattern (v, pattern, patspec, varname, quoted);
       if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
        {
          val = quote_escapes (temp1);
@@ -3738,12 +4302,18 @@ unlink_fifo_list ()
     nfifo = 0;
 }
 
+int
+fifos_pending ()
+{
+  return nfifo;
+}
+
 static char *
 make_named_pipe ()
 {
   char *tname;
 
-  tname = sh_mktmpname ("sh-np", MT_USERANDOM);
+  tname = sh_mktmpname ("sh-np", MT_USERANDOM|MT_USETMPDIR);
   if (mkfifo (tname, 0600) < 0)
     {
       free (tname);
@@ -3776,7 +4346,7 @@ add_fifo_list (fd)
       totfds = getdtablesize ();
       if (totfds < 0 || totfds > 256)
        totfds = 256;
-      if (fd > totfds)
+      if (fd >= totfds)
        totfds = fd + 2;
 
       dev_fd_list = (char *)xrealloc (dev_fd_list, totfds);
@@ -3787,6 +4357,12 @@ add_fifo_list (fd)
   nfds++;
 }
 
+int
+fifos_pending ()
+{
+  return 0;    /* used for cleanup; not needed with /dev/fd */
+}
+
 void
 unlink_fifo_list ()
 {
@@ -3891,7 +4467,7 @@ process_substitute (string, open_for_read_in_child)
   pathname = make_dev_fd_filename (parent_pipe_fd);
 #endif /* HAVE_DEV_FD */
 
-  if (!pathname)
+  if (pathname == 0)
     {
       sys_error (_("cannot make pipe for process substitution"));
       return ((char *)NULL);
@@ -3913,12 +4489,13 @@ process_substitute (string, open_for_read_in_child)
       /* Cancel traps, in trap.c. */
       restore_original_signals ();
       setup_async_signals ();
-      subshell_environment |= SUBSHELL_COMSUB;
+      subshell_environment |= SUBSHELL_COMSUB|SUBSHELL_PROCSUB;
     }
 
 #if defined (JOB_CONTROL)
   set_sigchld_handler ();
   stop_making_children ();
+  /* XXX - should we only do this in the parent? (as in command subst) */
   pipeline_pgrp = old_pipeline_pgrp;
 #endif /* JOB_CONTROL */
 
@@ -3979,7 +4556,7 @@ process_substitute (string, open_for_read_in_child)
     {
       if (sh_unset_nodelay_mode (fd) < 0)
        {
-         sys_error (_("cannout reset nodelay mode for fd %d"), fd);
+         sys_error (_("cannot reset nodelay mode for fd %d"), fd);
          exit (127);
        }
     }
@@ -4032,21 +4609,26 @@ process_substitute (string, open_for_read_in_child)
 /***********************************/
 
 static char *
-read_comsub (fd, quoted)
+read_comsub (fd, quoted, rflag)
      int fd, quoted;
+     int *rflag;
 {
-  char *istring, buf[128], *bufp;
-  int istring_index, istring_size, c;
+  char *istring, buf[128], *bufp, *s;
+  int istring_index, istring_size, c, tflag, skip_ctlesc, skip_ctlnul;
   ssize_t bufn;
 
   istring = (char *)NULL;
-  istring_index = istring_size = bufn = 0;
+  istring_index = istring_size = bufn = tflag = 0;
+
+  for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++)
+    skip_ctlesc |= *s == CTLESC, skip_ctlnul |= *s == CTLNUL;
 
 #ifdef __CYGWIN__
   setmode (fd, O_TEXT);                /* we don't want CR/LF, we want Unix-style */
 #endif
 
-  /* Read the output of the command through the pipe. */
+  /* Read the output of the command through the pipe.  This may need to be
+     changed to understand multibyte characters in the future. */
   while (1)
     {
       if (fd < 0)
@@ -4071,7 +4653,18 @@ read_comsub (fd, quoted)
       /* Add the character to ISTRING, possibly after resizing it. */
       RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE);
 
-      if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || c == CTLESC || c == CTLNUL)
+      /* This is essentially quote_string inline */
+      if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) /* || c == CTLESC || c == CTLNUL */)
+       istring[istring_index++] = CTLESC;
+      /* Escape CTLESC and CTLNUL in the output to protect those characters
+        from the rest of the word expansions (word splitting and globbing.)
+        This is essentially quote_escapes inline. */
+      else if (skip_ctlesc == 0 && c == CTLESC)
+       {
+         tflag |= W_HASCTLESC;
+         istring[istring_index++] = CTLESC;
+       }
+      else if ((skip_ctlnul == 0 && c == CTLNUL) || (c == ' ' && (ifs_value && *ifs_value == 0)))
        istring[istring_index++] = CTLESC;
 
       istring[istring_index++] = c;
@@ -4095,6 +4688,8 @@ read_comsub (fd, quoted)
   if (istring_index == 0)
     {
       FREE (istring);
+      if (rflag)
+       *rflag = tflag;
       return (char *)NULL;
     }
 
@@ -4119,26 +4714,29 @@ read_comsub (fd, quoted)
   else
     strip_trailing (istring, istring_index - 1, 1);
 
+  if (rflag)
+    *rflag = tflag;
   return istring;
 }
 
-/* Perform command substitution on STRING.  This returns a string,
-   possibly quoted. */
-char *
+/* Perform command substitution on STRING.  This returns a WORD_DESC * with the
+   contained string possibly quoted. */
+WORD_DESC *
 command_substitute (string, quoted)
      char *string;
      int quoted;
 {
-  pid_t pid, old_pid, old_pipeline_pgrp;
+  pid_t pid, old_pid, old_pipeline_pgrp, old_async_pid;
   char *istring;
-  int result, fildes[2], function_value, pflags, rc;
+  int result, fildes[2], function_value, pflags, rc, tflag;
+  WORD_DESC *ret;
 
   istring = (char *)NULL;
 
   /* Don't fork () if there is no need to.  In the case of no command to
      run, just return NULL. */
   if (!string || !*string || (string[0] == '\n' && !string[1]))
-    return ((char *)NULL);
+    return ((WORD_DESC *)NULL);
 
   if (wordexp_only && read_but_dont_execute)
     {
@@ -4175,18 +4773,23 @@ command_substitute (string, quoted)
   if ((subshell_environment & SUBSHELL_PIPE) == 0)
     pipeline_pgrp = shell_pgrp;
   cleanup_the_pipeline ();
-#endif
+#endif /* JOB_CONTROL */
+
+  old_async_pid = last_asynchronous_pid;
+  pid = make_child ((char *)NULL, subshell_environment&SUBSHELL_ASYNC);
+  last_asynchronous_pid = old_async_pid;
 
-  pid = make_child ((char *)NULL, 0);
   if (pid == 0)
     /* Reset the signal handlers in the child, but don't free the
        trap strings. */
     reset_signal_handlers ();
 
 #if defined (JOB_CONTROL)
+  /* XXX DO THIS ONLY IN PARENT ? XXX */
   set_sigchld_handler ();
   stop_making_children ();
-  pipeline_pgrp = old_pipeline_pgrp;
+  if (pid != 0)
+    pipeline_pgrp = old_pipeline_pgrp;
 #else
   stop_making_children ();
 #endif /* JOB_CONTROL */
@@ -4199,7 +4802,7 @@ command_substitute (string, quoted)
       FREE (istring);
       close (fildes[0]);
       close (fildes[1]);
-      return ((char *)NULL);
+      return ((WORD_DESC *)NULL);
     }
 
   if (pid == 0)
@@ -4273,6 +4876,9 @@ command_substitute (string, quoted)
 
       last_command_exit_value = rc;
       rc = run_exit_trap ();
+#if defined (PROCESS_SUBSTITUTION)
+      unlink_fifo_list ();
+#endif
       exit (rc);
     }
   else
@@ -4283,7 +4889,8 @@ command_substitute (string, quoted)
 
       close (fildes[1]);
 
-      istring = read_comsub (fildes[0], quoted);
+      tflag = 0;
+      istring = read_comsub (fildes[0], quoted, &tflag);
 
       close (fildes[0]);
 
@@ -4313,7 +4920,11 @@ command_substitute (string, quoted)
        give_terminal_to (pipeline_pgrp, 0);
 #endif /* JOB_CONTROL */
 
-      return (istring);
+      ret = alloc_word_desc ();
+      ret->word = istring;
+      ret->flags = tflag;
+
+      return ret;
     }
 }
 
@@ -4331,6 +4942,7 @@ array_length_reference (s)
 {
   int len;
   arrayind_t ind;
+  char *akey;
   char *t, c;
   ARRAY *array;
   SHELL_VAR *var;
@@ -4339,7 +4951,7 @@ array_length_reference (s)
 
   /* If unbound variables should generate an error, report one and return
      failure. */
-  if ((var == 0 || array_p (var) == 0) && unbound_vars_is_error)
+  if ((var == 0 || (assoc_p (var) == 0 && array_p (var) == 0)) && unbound_vars_is_error)
     {
       c = *--t;
       *t = '\0';
@@ -4357,21 +4969,42 @@ array_length_reference (s)
   array = array_p (var) ? array_cell (var) : (ARRAY *)NULL;
 
   if (ALL_ELEMENT_SUB (t[0]) && t[1] == ']')
-    return (array_p (var) ? array_num_elements (array) : 1);
-
-  ind = array_expand_index (t, len);
-  if (ind < 0)
     {
-      err_badarraysub (t);
-      return (-1);
+      if (assoc_p (var))
+       return (assoc_num_elements (assoc_cell (var)));
+      else if (array_p (var))
+       return (array_num_elements (array));
+      else
+       return 1;
     }
 
-  if (array_p (var))
-    t = array_reference (array, ind);
+  if (assoc_p (var))
+    {
+      t[len - 1] = '\0';
+      akey = expand_assignment_string_to_string (t, 0);        /* [ */
+      t[len - 1] = ']';
+      if (akey == 0 || *akey == 0)
+       {
+         err_badarraysub (t);
+         return (-1);
+       }
+      t = assoc_reference (assoc_cell (var), akey);
+    }
   else
-    t = (ind == 0) ? value_cell (var) : (char *)NULL;
+    {
+      ind = array_expand_index (t, len);
+      if (ind < 0)
+       {
+         err_badarraysub (t);
+         return (-1);
+       }
+      if (array_p (var))
+       t = array_reference (array, ind);
+      else
+       t = (ind == 0) ? value_cell (var) : (char *)NULL;
+    }
 
-  len = STRLEN (t);
+  len = MB_STRLEN (t);
   return (len);
 }
 #endif /* ARRAY_VARS */
@@ -4459,18 +5092,22 @@ chk_atstar (name, quoted, quoted_dollar_atp, contains_dollar_at)
    VAR_IS_SPECIAL is non-zero if NAME is one of the special variables in
    the shell, e.g., "@", "$", "*", etc.  QUOTED, if non-zero, means that
    NAME was found inside of a double-quoted expression. */
-static char *
+static WORD_DESC *
 parameter_brace_expand_word (name, var_is_special, quoted)
      char *name;
      int var_is_special, quoted;
 {
+  WORD_DESC *ret;
   char *temp, *tt;
   intmax_t arg_index;
   SHELL_VAR *var;
-  int atype;
+  int atype, rflags;
 
-  /* Handle multiple digit arguments, as in ${11}. */
-  
+  ret = 0;
+  temp = 0;
+  rflags = 0;
+
+  /* Handle multiple digit arguments, as in ${11}. */  
   if (legal_number (name, &arg_index))
     {
       tt = get_dollar_var_value (arg_index);
@@ -4489,8 +5126,8 @@ parameter_brace_expand_word (name, var_is_special, quoted)
       tt[sindex = 0] = '$';
       strcpy (tt + 1, name);
 
-      temp = param_expand (tt, &sindex, quoted, (int *)NULL, (int *)NULL,
-                          (int *)NULL, (int *)NULL, 0);
+      ret = param_expand (tt, &sindex, quoted, (int *)NULL, (int *)NULL,
+                         (int *)NULL, (int *)NULL, 0);
       free (tt);
     }
 #if defined (ARRAY_VARS)
@@ -4501,6 +5138,8 @@ parameter_brace_expand_word (name, var_is_special, quoted)
        temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
                  ? quote_string (temp)
                  : quote_escapes (temp);
+      else if (atype == 1 && temp && QUOTED_NULL (temp) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
+       rflags |= W_HASQUOTEDNULL;
     }
 #endif
   else if (var = find_variable (name))
@@ -4508,7 +5147,12 @@ parameter_brace_expand_word (name, var_is_special, quoted)
       if (var_isset (var) && invisible_p (var) == 0)
        {
 #if defined (ARRAY_VARS)
-         temp = array_p (var) ? array_reference (array_cell (var), 0) : value_cell (var);
+         if (assoc_p (var))
+           temp = assoc_reference (assoc_cell (var), "0");
+         else if (array_p (var))
+           temp = array_reference (array_cell (var), 0);
+         else
+           temp = value_cell (var);
 #else
          temp = value_cell (var);
 #endif
@@ -4524,20 +5168,28 @@ parameter_brace_expand_word (name, var_is_special, quoted)
   else
     temp = (char *)NULL;
 
-  return (temp);
+  if (ret == 0)
+    {
+      ret = alloc_word_desc ();
+      ret->word = temp;
+      ret->flags |= rflags;
+    }
+  return ret;
 }
 
 /* Expand an indirect reference to a variable: ${!NAME} expands to the
    value of the variable whose name is the value of NAME. */
-static char *
+static WORD_DESC *
 parameter_brace_expand_indir (name, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at)
      char *name;
      int var_is_special, quoted;
      int *quoted_dollar_atp, *contains_dollar_at;
 {
   char *temp, *t;
+  WORD_DESC *w;
 
-  t = parameter_brace_expand_word (name, var_is_special, quoted);
+  w = parameter_brace_expand_word (name, var_is_special, quoted);
+  t = w->word;
   /* Have to dequote here if necessary */
   if (t)
     {
@@ -4547,53 +5199,52 @@ parameter_brace_expand_indir (name, var_is_special, quoted, quoted_dollar_atp, c
       free (t);
       t = temp;
     }
+  dispose_word_desc (w);
+
   chk_atstar (t, quoted, quoted_dollar_atp, contains_dollar_at);
   if (t == 0)
-    return (t);
-  temp = parameter_brace_expand_word (t, SPECIAL_VAR(t, 0), quoted);
+    return (WORD_DESC *)NULL;
+
+  w = parameter_brace_expand_word (t, SPECIAL_VAR(t, 0), quoted);
   free (t);
-  return temp;
+
+  return w;
 }
 
 /* Expand the right side of a parameter expansion of the form ${NAMEcVALUE},
    depending on the value of C, the separating character.  C can be one of
    "-", "+", or "=".  QUOTED is true if the entire brace expression occurs
    between double quotes. */
-static char *
+static WORD_DESC *
 parameter_brace_expand_rhs (name, value, c, quoted, qdollaratp, hasdollarat)
      char *name, *value;
      int c, quoted, *qdollaratp, *hasdollarat;
 {
+  WORD_DESC *w;
   WORD_LIST *l;
   char *t, *t1, *temp;
   int hasdol;
 
-  /* XXX - Should we tilde expand in an assignment context if C is `='? */
-  if (*value == '~')
-    temp = bash_tilde_expand (value, 0);
-  else if (xstrchr (value, '~')  && unquoted_substring ("=~", value))
-    temp = bash_tilde_expand (value, 1);
-  else
-    temp = savestring (value);
-
   /* If the entire expression is between double quotes, we want to treat
      the value as a double-quoted string, with the exception that we strip
-     embedded unescaped double quotes. */
-  if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *temp)
+     embedded unescaped double quotes (for sh backwards compatibility). */
+  if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *value)
     {
       hasdol = 0;
-      t = string_extract_double_quoted (temp, &hasdol, 1);
-      free (temp);
-      temp = t;
+      temp = string_extract_double_quoted (value, &hasdol, 1);
     }
+  else
+    temp = value;
 
+  w = alloc_word_desc ();
   hasdol = 0;
   /* XXX was 0 not quoted */
   l = *temp ? expand_string_for_rhs (temp, quoted, &hasdol, (int *)NULL)
            : (WORD_LIST *)0;
   if (hasdollarat)
     *hasdollarat = hasdol || (l && l->next);
-  free (temp);
+  if (temp != value)
+    free (temp);
   if (l)
     {
       /* The expansion of TEMP returned something.  We need to treat things
@@ -4616,15 +5267,17 @@ parameter_brace_expand_rhs (name, value, c, quoted, qdollaratp, hasdollarat)
         a $@ in TEMP.  It does not matter if the $@ is quoted, as long as
         it does not expand to anything.  In this case, we want to return
         a quoted empty string. */
-      temp = (char *)xmalloc (2);
-      temp[0] = CTLNUL;
-      temp[1] = '\0';
+      temp = make_quoted_char ('\0');
+      w->flags |= W_HASQUOTEDNULL;
     }
   else
     temp = (char *)NULL;
 
   if (c == '-' || c == '+')
-    return (temp);
+    {
+      w->word = temp;
+      return w;
+    }
 
   /* c == '=' */
   t = temp ? savestring (temp) : savestring ("");
@@ -4632,12 +5285,14 @@ parameter_brace_expand_rhs (name, value, c, quoted, qdollaratp, hasdollarat)
   free (t);
 #if defined (ARRAY_VARS)
   if (valid_array_reference (name))
-    assign_array_element (name, t1);
+    assign_array_element (name, t1, 0);
   else
 #endif /* ARRAY_VARS */
-  bind_variable (name, t1);
+  bind_variable (name, t1, 0);
   free (t1);
-  return (temp);
+
+  w->word = temp;
+  return w;
 }
 
 /* Deal with the right hand side of a ${name:?value} expansion in the case
@@ -4653,15 +5308,7 @@ parameter_brace_expand_error (name, value)
 
   if (value && *value)
     {
-      if (*value == '~')
-       temp = bash_tilde_expand (value, 0);
-      else if (xstrchr (value, '~')  && unquoted_substring ("=~", value))
-       temp = bash_tilde_expand (value, 1);
-      else
-       temp = savestring (value);
-
-      l = expand_string (temp, 0);
-      FREE (temp);
+      l = expand_string (value, 0);
       temp =  string_list (l);
       report_error ("%s: %s", name, temp ? temp : ""); /* XXX was value not "" */
       FREE (temp);
@@ -4691,6 +5338,34 @@ valid_length_expression (name)
          legal_identifier (name + 1));                         /* ${#PS1} */
 }
 
+#if defined (HANDLE_MULTIBYTE)
+size_t
+mbstrlen (s)
+     const char *s;
+{
+  size_t clen, nc;
+  mbstate_t mbs, mbsbak;
+
+  nc = 0;
+  memset (&mbs, 0, sizeof (mbs));
+  mbsbak = mbs;
+  while ((clen = mbrlen(s, MB_CUR_MAX, &mbs)) != 0)
+    {
+      if (MB_INVALIDCH(clen))
+        {
+         clen = 1;     /* assume single byte */
+         mbs = mbsbak;
+        }
+
+      s += clen;
+      nc++;
+      mbsbak = mbs;
+    }
+  return nc;
+}
+#endif
+      
+
 /* Handle the parameter brace expansion that requires us to return the
    length of a parameter. */
 static intmax_t
@@ -4746,14 +5421,17 @@ parameter_brace_expand_length (name)
       if (legal_number (name + 1, &arg_index))         /* ${#1} */
        {
          t = get_dollar_var_value (arg_index);
-         number = STRLEN (t);
+         number = MB_STRLEN (t);
          FREE (t);
        }
 #if defined (ARRAY_VARS)
-      else if ((var = find_variable (name + 1)) && array_p (var))
+      else if ((var = find_variable (name + 1)) && (invisible_p (var) == 0) && (array_p (var) || assoc_p (var)))
        {
-         t = array_reference (array_cell (var), 0);
-         number = STRLEN (t);
+         if (assoc_p (var))
+           t = assoc_reference (assoc_cell (var), "0");
+         else
+           t = array_reference (array_cell (var), 0);
+         number = MB_STRLEN (t);
        }
 #endif
       else                             /* ${#PS1} */
@@ -4766,7 +5444,7 @@ parameter_brace_expand_length (name)
          if (list)
            dispose_words (list);
 
-         number = STRLEN (t);
+         number = MB_STRLEN (t);
          FREE (t);
        }
     }
@@ -4841,7 +5519,8 @@ skiparith (substr, delim)
    Return value is 1 if both values were OK, 0 if there was a problem
    with an invalid expression, or -1 if the values were out of range. */
 static int
-verify_substring_values (value, substr, vtype, e1p, e2p)
+verify_substring_values (v, value, substr, vtype, e1p, e2p)
+     SHELL_VAR *v;
      char *value, *substr;
      int vtype;
      intmax_t *e1p, *e2p;
@@ -4851,6 +5530,7 @@ verify_substring_values (value, substr, vtype, e1p, e2p)
   int expok;
 #if defined (ARRAY_VARS)
  ARRAY *a;
+ HASH_TABLE *h;
 #endif
 
   /* duplicate behavior of strchr(3) */
@@ -4860,7 +5540,7 @@ verify_substring_values (value, substr, vtype, e1p, e2p)
   else
     t = (char *)0;
 
-  temp1 = expand_string_if_necessary (substr, Q_DOUBLE_QUOTES, expand_string);
+  temp1 = expand_arith_string (substr, Q_DOUBLE_QUOTES);
   *e1p = evalexp (temp1, &expok);
   free (temp1);
   if (expok == 0)
@@ -4871,16 +5551,28 @@ verify_substring_values (value, substr, vtype, e1p, e2p)
     {
     case VT_VARIABLE:
     case VT_ARRAYMEMBER:
-      len = strlen (value);
+      len = MB_STRLEN (value);
       break;
     case VT_POSPARMS:
       len = number_of_args () + 1;
+      if (*e1p == 0)
+       len++;          /* add one arg if counting from $0 */
       break;
 #if defined (ARRAY_VARS)
     case VT_ARRAYVAR:
-      a = (ARRAY *)value;
-      /* For arrays, the first value deals with array indices. */
-      len = array_max_index (a);       /* arrays index from 0 to n - 1 */
+      /* For arrays, the first value deals with array indices.  Negative
+        offsets count from one past the array's maximum index.  Associative
+        arrays treat the number of elements as the maximum index. */
+      if (assoc_p (v))
+       {
+         h = assoc_cell (v);
+         len = assoc_num_elements (h) + (*e1p < 0);
+       }
+      else
+       {
+         a = (ARRAY *)value;
+         len = array_max_index (a) + (*e1p < 0);       /* arrays index from 0 to n - 1 */
+       }
       break;
 #endif
     }
@@ -4891,20 +5583,20 @@ verify_substring_values (value, substr, vtype, e1p, e2p)
   if (*e1p < 0)                /* negative offsets count from end */
     *e1p += len;
 
-  if (*e1p >= len || *e1p < 0)
+  if (*e1p > len || *e1p < 0)
     return (-1);
 
 #if defined (ARRAY_VARS)
   /* For arrays, the second offset deals with the number of elements. */
   if (vtype == VT_ARRAYVAR)
-    len = array_num_elements (a);
+    len = assoc_p (v) ? assoc_num_elements (h) : array_num_elements (a);
 #endif
 
   if (t)
     {
       t++;
       temp2 = savestring (t);
-      temp1 = expand_string_if_necessary (temp2, Q_DOUBLE_QUOTES, expand_string);
+      temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES);
       free (temp2);
       t[-1] = ':';
       *e2p = evalexp (temp1, &expok);
@@ -4963,14 +5655,15 @@ get_var_and_type (varname, value, quoted, varp, valp)
   if (valid_array_reference (varname))
     {
       v = array_variable_part (varname, &temp, (int *)0);
-      if (v && array_p (v))
+      if (v && (array_p (v) || assoc_p (v)))
        { /* [ */
          if (ALL_ELEMENT_SUB (temp[0]) && temp[1] == ']')
            {
+             /* Callers have to differentiate betwen indexed and associative */
              vtype = VT_ARRAYVAR;
              if (temp[0] == '*')
                vtype |= VT_STARSUB;
-             *valp = (char *)array_cell (v);
+             *valp = array_p (v) ? (char *)array_cell (v) : (char *)assoc_cell (v);
            }
          else
            {
@@ -4979,18 +5672,30 @@ get_var_and_type (varname, value, quoted, varp, valp)
            }
          *varp = v;
        }
+      else if (v && (ALL_ELEMENT_SUB (temp[0]) && temp[1] == ']'))
+       {
+         vtype = VT_VARIABLE;
+         *varp = v;
+         if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
+           *valp = dequote_string (value);
+         else
+           *valp = dequote_escapes (value);
+       }
       else
-       return -1;
+       {
+         vtype = VT_ARRAYMEMBER;
+         *varp = v;
+         *valp = array_value (varname, 1, (int *)NULL);
+       }
     }
-  else if ((v = find_variable (varname)) && array_p (v))
+  else if ((v = find_variable (varname)) && (invisible_p (v) == 0) && (assoc_p (v) || array_p (v)))
     {
       vtype = VT_ARRAYMEMBER;
       *varp = v;
-      *valp = array_reference (array_cell (v), 0);
+      *valp = assoc_p (v) ? assoc_reference (assoc_cell (v), "0") : array_reference (array_cell (v), 0);
     }
   else
 #endif
-#if 1
     {
       if (value && vtype == VT_VARIABLE)
        {
@@ -5002,9 +5707,6 @@ get_var_and_type (varname, value, quoted, varp, valp)
       else
        *valp = value;
     }
-#else
-  *valp = (value && vtype == VT_VARIABLE) ? dequote_escapes (value) : value;
-#endif
 
   return vtype;
 }
@@ -5030,7 +5732,8 @@ mb_substring (string, s, e)
   DECLARE_MBSTATE;
 
   start = 0;
-  slen = STRLEN (string);
+  /* Don't need string length in ADVANCE_CHAR unless multibyte chars possible. */
+  slen = (MB_CUR_MAX > 1) ? STRLEN (string) : 0;
 
   i = s;
   while (string[start] && i--)
@@ -5055,22 +5758,27 @@ parameter_brace_substring (varname, value, substr, quoted)
 {
   intmax_t e1, e2;
   int vtype, r, starsub;
-  char *temp, *val, *tt;
+  char *temp, *val, *tt, *oname;
   SHELL_VAR *v;
 
   if (value == 0)
     return ((char *)NULL);
 
+  oname = this_command_name;
   this_command_name = varname;
 
   vtype = get_var_and_type (varname, value, quoted, &v, &val);
   if (vtype == -1)
-    return ((char *)NULL);
+    {
+      this_command_name = oname;
+      return ((char *)NULL);
+    }
 
   starsub = vtype & VT_STARSUB;
   vtype &= ~VT_STARSUB;
 
-  r = verify_substring_values (val, substr, vtype, &e1, &e2);
+  r = verify_substring_values (v, val, substr, vtype, &e1, &e2);
+  this_command_name = oname;
   if (r <= 0)
     return ((r == 0) ? &expand_param_error : (char *)NULL);
 
@@ -5105,17 +5813,17 @@ parameter_brace_substring (varname, value, substr, quoted)
       break;
 #if defined (ARRAY_VARS)
     case VT_ARRAYVAR:
+      if (assoc_p (v))
+       /* we convert to list and take first e2 elements starting at e1th
+          element -- officially undefined for now */   
+       temp = assoc_subrange (assoc_cell (v), e1, e2, starsub, quoted);
+      else
       /* We want E2 to be the number of elements desired (arrays can be sparse,
         so verify_substring_values just returns the numbers specified and we
         rely on array_subrange to understand how to deal with them). */
-      tt = array_subrange (array_cell (v), e1, e2, starsub, quoted);
-      if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0)
-       {
-         temp = tt ? quote_escapes (tt) : (char *)NULL;
-         FREE (tt);
-       }
-      else
-       temp = tt;
+       temp = array_subrange (array_cell (v), e1, e2, starsub, quoted);
+      /* array_subrange now calls array_quote_escapes as appropriate, so the
+        caller no longer needs to. */
       break;
 #endif
     default:
@@ -5220,7 +5928,8 @@ pos_params_pat_subst (string, pat, rep, mflags)
 {
   WORD_LIST *save, *params;
   WORD_DESC *w;
-  char *ret, *tt;
+  char *ret;
+  int pchar, qflags;
 
   save = params = list_rest_of_args ();
   if (save == 0)
@@ -5229,16 +5938,28 @@ pos_params_pat_subst (string, pat, rep, mflags)
   for ( ; params; params = params->next)
     {
       ret = pat_subst (params->word->word, pat, rep, mflags);
-      w = make_bare_word (ret);
+      w = alloc_word_desc ();
+      w->word = ret ? ret : savestring ("");
       dispose_word (params->word);
       params->word = w;
-      FREE (ret);
     }
 
+  pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
+  qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
+
+#if 0
   if ((mflags & (MATCH_QUOTED|MATCH_STARSUB)) == (MATCH_QUOTED|MATCH_STARSUB))
     ret = string_list_dollar_star (quote_list (save));
+  else if ((mflags & MATCH_STARSUB) == MATCH_STARSUB)
+    ret = string_list_dollar_star (save);
+  else if ((mflags & MATCH_QUOTED) == MATCH_QUOTED)
+    ret = string_list_dollar_at (save, qflags);
   else
-    ret = string_list ((mflags & MATCH_QUOTED) ? quote_list (save) : save);
+    ret = string_list_dollar_star (save);
+#else
+  ret = string_list_pos_params (pchar, save, qflags);
+#endif
+
   dispose_words (save);
 
   return (ret);
@@ -5253,7 +5974,7 @@ parameter_brace_patsub (varname, value, patsub, quoted)
      char *varname, *value, *patsub;
      int quoted;
 {
-  int vtype, mflags, starsub;
+  int vtype, mflags, starsub, delim;
   char *val, *temp, *pat, *rep, *p, *lpatsub, *tt;
   SHELL_VAR *v;
 
@@ -5270,7 +5991,7 @@ parameter_brace_patsub (varname, value, patsub, quoted)
   vtype &= ~VT_STARSUB;
 
   mflags = 0;
-  if (*patsub == '/')
+  if (patsub && *patsub == '/')
     {
       mflags |= MATCH_GLOBREP;
       patsub++;
@@ -5286,126 +6007,348 @@ parameter_brace_patsub (varname, value, patsub, quoted)
   if (starsub)
     mflags |= MATCH_STARSUB;
 
-  if (rep = quoted_strchr (lpatsub, '/', ST_BACKSL))
+  /* If the pattern starts with a `/', make sure we skip over it when looking
+     for the replacement delimiter. */
+#if 0
+  if (rep = quoted_strchr ((*patsub == '/') ? lpatsub+1 : lpatsub, '/', ST_BACKSL))
     *rep++ = '\0';
   else
     rep = (char *)NULL;
+#else
+  delim = skip_to_delim (lpatsub, ((*patsub == '/') ? 1 : 0), "/", 0);
+  if (lpatsub[delim] == '/')
+    {
+      lpatsub[delim] = 0;
+      rep = lpatsub + delim + 1;
+    }
+  else
+    rep = (char *)NULL;
+#endif
 
   if (rep && *rep == '\0')
     rep = (char *)NULL;
 
-#if 0
-  /* Expand PAT and REP for command, variable and parameter, arithmetic,
-     and process substitution.  Also perform quote removal.  Do not
-     perform word splitting or filename generation. */
-  pat = expand_string_if_necessary (lpatsub, (quoted & ~Q_DOUBLE_QUOTES), expand_string_unsplit);
-#else
   /* Perform the same expansions on the pattern as performed by the
      pattern removal expansions. */
   pat = getpattern (lpatsub, quoted, 1);
+
+  if (rep)
+    {
+      if ((mflags & MATCH_QUOTED) == 0)
+       rep = expand_string_if_necessary (rep, quoted, expand_string_unsplit);
+      else
+       rep = expand_string_to_string_internal (rep, quoted, expand_string_unsplit);
+    }
+
+  /* ksh93 doesn't allow the match specifier to be a part of the expanded
+     pattern.  This is an extension.  Make sure we don't anchor the pattern
+     at the beginning or end of the string if we're doing global replacement,
+     though. */
+  p = pat;
+  if (mflags & MATCH_GLOBREP)
+    mflags |= MATCH_ANY;
+  else if (pat && pat[0] == '#')
+    {
+      mflags |= MATCH_BEG;
+      p++;
+    }
+  else if (pat && pat[0] == '%')
+    {
+      mflags |= MATCH_END;
+      p++;
+    }
+  else
+    mflags |= MATCH_ANY;
+
+  /* OK, we now want to substitute REP for PAT in VAL.  If
+     flags & MATCH_GLOBREP is non-zero, the substitution is done
+     everywhere, otherwise only the first occurrence of PAT is
+     replaced.  The pattern matching code doesn't understand
+     CTLESC quoting CTLESC and CTLNUL so we use the dequoted variable
+     values passed in (VT_VARIABLE) so the pattern substitution
+     code works right.  We need to requote special chars after
+     we're done for VT_VARIABLE and VT_ARRAYMEMBER, and for the
+     other cases if QUOTED == 0, since the posparams and arrays
+     indexed by * or @ do special things when QUOTED != 0. */
+
+  switch (vtype)
+    {
+    case VT_VARIABLE:
+    case VT_ARRAYMEMBER:
+      temp = pat_subst (val, p, rep, mflags);
+      if (vtype == VT_VARIABLE)
+       FREE (val);
+      if (temp)
+       {
+         tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
+         free (temp);
+         temp = tt;
+       }
+      break;
+    case VT_POSPARMS:
+      temp = pos_params_pat_subst (val, p, rep, mflags);
+      if (temp && (mflags & MATCH_QUOTED) == 0)
+       {
+         tt = quote_escapes (temp);
+         free (temp);
+         temp = tt;
+       }
+      break;
+#if defined (ARRAY_VARS)
+    case VT_ARRAYVAR:
+      temp = assoc_p (v) ? assoc_patsub (assoc_cell (v), p, rep, mflags)
+                        : array_patsub (array_cell (v), p, rep, mflags);
+      /* Don't call quote_escapes anymore; array_patsub calls
+        array_quote_escapes as appropriate before adding the
+        space separators; ditto for assoc_patsub. */
+      break;
 #endif
+    }
+
+  FREE (pat);
+  FREE (rep);
+  free (lpatsub);
+
+  return temp;
+}
+
+/****************************************************************/
+/*                                                             */
+/*   Functions to perform case modification on variable values  */
+/*                                                             */
+/****************************************************************/
+
+/* Do case modification on the positional parameters. */
+
+static char *
+pos_params_modcase (string, pat, modop, mflags)
+     char *string, *pat;
+     int modop;
+     int mflags;
+{
+  WORD_LIST *save, *params;
+  WORD_DESC *w;
+  char *ret;
+  int pchar, qflags;
+
+  save = params = list_rest_of_args ();
+  if (save == 0)
+    return ((char *)NULL);
+
+  for ( ; params; params = params->next)
+    {
+      ret = sh_modcase (params->word->word, pat, modop);
+      w = alloc_word_desc ();
+      w->word = ret ? ret : savestring ("");
+      dispose_word (params->word);
+      params->word = w;
+    }
+
+  pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
+  qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
+
+  ret = string_list_pos_params (pchar, save, qflags);
+  dispose_words (save);
+
+  return (ret);
+}
+
+/* Perform case modification on VALUE, which is the expansion of
+   VARNAME.  MODSPEC is an expression supplying the type of modification
+   to perform.  QUOTED is a flags word containing the type of quoting
+   currently in effect. */
+static char *
+parameter_brace_casemod (varname, value, modspec, patspec, quoted)
+     char *varname, *value;
+     int modspec;
+     char *patspec;
+     int quoted;
+{
+  int vtype, starsub, modop, mflags, x;
+  char *val, *temp, *pat, *p, *lpat, *tt;
+  SHELL_VAR *v;
+
+  if (value == 0)
+    return ((char *)NULL);
+
+  this_command_name = varname;
+
+  vtype = get_var_and_type (varname, value, quoted, &v, &val);
+  if (vtype == -1)
+    return ((char *)NULL);
+
+  starsub = vtype & VT_STARSUB;
+  vtype &= ~VT_STARSUB;
 
-  if (rep)
+  modop = 0;
+  mflags = 0;
+  if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
+    mflags |= MATCH_QUOTED;
+  if (starsub)
+    mflags |= MATCH_STARSUB;
+  
+  p = patspec;
+  if (modspec == '^')
     {
-      if ((mflags & MATCH_QUOTED) == 0)
-       rep = expand_string_if_necessary (rep, quoted, expand_string_unsplit);
-      else
-       rep = expand_string_to_string_internal (rep, quoted, expand_string_unsplit);
+      x = p && p[0] == modspec;
+      modop = x ? CASE_UPPER : CASE_CAPITALIZE;
+      p += x;
     }
-
-  p = pat;
-  if (pat && pat[0] == '#')
+  else if (modspec == ',')
     {
-      mflags |= MATCH_BEG;
-      p++;
+      x = p && p[0] == modspec;
+      modop = x ? CASE_LOWER : CASE_UNCAP;
+      p += x;
     }
-  else if (pat && pat[0] == '%')
+  else if (modspec == '~')
     {
-      mflags |= MATCH_END;
-      p++;
+      x = p && p[0] == modspec;
+      modop = x ? CASE_TOGGLEALL : CASE_TOGGLE;
+      p += x;
     }
-  else
-    mflags |= MATCH_ANY;
-
-  /* OK, we now want to substitute REP for PAT in VAL.  If
-     flags & MATCH_GLOBREP is non-zero, the substitution is done
-     everywhere, otherwise only the first occurrence of PAT is
-     replaced.  The pattern matching code doesn't understand
-     CTLESC quoting CTLESC and CTLNUL so we use the dequoted variable
-     values passed in (VT_VARIABLE) so the pattern substitution
-     code works right.  We need to requote special chars after
-     we're done for VT_VARIABLE and VT_ARRAYMEMBER, and for the
-     other cases if QUOTED == 0, since the posparams and arrays
-     indexed by * or @ do special things when QUOTED != 0. */
+    
+  lpat = p ? savestring (p) : 0;
+  /* Perform the same expansions on the pattern as performed by the
+     pattern removal expansions.  FOR LATER */
+  pat = lpat ? getpattern (lpat, quoted, 1) : 0;
 
+  /* OK, now we do the case modification. */
   switch (vtype)
     {
     case VT_VARIABLE:
     case VT_ARRAYMEMBER:
-      temp = pat_subst (val, p, rep, mflags);
+      temp = sh_modcase (val, pat, modop);
       if (vtype == VT_VARIABLE)
        FREE (val);
       if (temp)
        {
-         tt = quote_escapes (temp);
+         tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
          free (temp);
          temp = tt;
        }
       break;
+
     case VT_POSPARMS:
-      temp = pos_params_pat_subst (val, p, rep, mflags);
-      if (temp && (mflags & MATCH_QUOTED) == 0)
+      temp = pos_params_modcase (val, pat, modop, mflags);
+      if (temp && (mflags & MATCH_QUOTED)  == 0)
        {
          tt = quote_escapes (temp);
          free (temp);
          temp = tt;
        }
       break;
+
 #if defined (ARRAY_VARS)
     case VT_ARRAYVAR:
-      temp = array_patsub (array_cell (v), p, rep, mflags);
-      if (temp && (mflags & MATCH_QUOTED) == 0)
-       {
-         tt = quote_escapes (temp);
-         free (temp);
-         temp = tt;
-       }
+      temp = assoc_p (v) ? assoc_modcase (assoc_cell (v), pat, modop, mflags)
+                        : array_modcase (array_cell (v), pat, modop, mflags);
+      /* Don't call quote_escapes; array_modcase calls array_quote_escapes
+        as appropriate before adding the space separators; ditto for
+        assoc_modcase. */
       break;
 #endif
     }
 
   FREE (pat);
-  FREE (rep);
-  free (lpatsub);
+  free (lpat);
 
   return temp;
 }
 
+/* Check for unbalanced parens in S, which is the contents of $(( ... )).  If
+   any occur, this must be a nested command substitution, so return 0.
+   Otherwise, return 1.  A valid arithmetic expression must always have a
+   ( before a matching ), so any cases where there are more right parens
+   means that this must not be an arithmetic expression, though the parser
+   will not accept it without a balanced total number of parens. */
+static int
+chk_arithsub (s, len)
+     const char *s;
+     int len;
+{
+  int i, count;
+  DECLARE_MBSTATE;
+
+  i = count = 0;
+  while (i < len)
+    {
+      if (s[i] == '(')
+       count++;
+      else if (s[i] == ')')
+       {
+         count--;
+         if (count < 0)
+           return 0;
+       }
+
+      switch (s[i])
+       {
+       default:
+         ADVANCE_CHAR (s, len, i);
+         break;
+
+       case '\\':
+         i++;
+         if (s[i])
+           ADVANCE_CHAR (s, len, i);
+         break;
+
+       case '\'':
+         i = skip_single_quoted (s, len, ++i);
+         break;
+
+       case '"':
+         i = skip_double_quoted ((char *)s, len, ++i);
+         break;
+       }
+    }
+
+  return (count == 0);
+}
+
 /****************************************************************/
 /*                                                             */
 /*     Functions to perform parameter expansion on a string    */
 /*                                                             */
 /****************************************************************/
 
-/* ${[#][!]name[[:]#[#]%[%]-=?+[word][:e1[:e2]]]} */
-static char *
+/* ${[#][!]name[[:][^[^]][,[,]]#[#]%[%]-=?+[word][:e1[:e2]]]} */
+static WORD_DESC *
 parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_dollar_at)
      char *string;
      int *indexp, quoted, *quoted_dollar_atp, *contains_dollar_at;
 {
   int check_nullness, var_is_set, var_is_null, var_is_special;
-  int want_substring, want_indir, want_patsub;
+  int want_substring, want_indir, want_patsub, want_casemod;
   char *name, *value, *temp, *temp1;
-  int t_index, sindex, c;
+  WORD_DESC *tdesc, *ret;
+  int t_index, sindex, c, tflag, modspec;
   intmax_t number;
 
-  value = (char *)NULL;
+  temp = temp1 = value = (char *)NULL;
   var_is_set = var_is_null = var_is_special = check_nullness = 0;
-  want_substring = want_indir = want_patsub = 0;
+  want_substring = want_indir = want_patsub = want_casemod = 0;
 
   sindex = *indexp;
   t_index = ++sindex;
-  name = string_extract (string, &t_index, "#%:-=?+/}", EX_VARNAME);
+  /* ${#var} doesn't have any of the other parameter expansions on it. */
+  if (string[t_index] == '#' && legal_variable_starter (string[t_index+1]))            /* {{ */
+    name = string_extract (string, &t_index, "}", SX_VARNAME);
+  else
+#if defined (CASEMOD_EXPANSIONS)
+    /* To enable case-toggling expansions using the `~' operator character
+       change the 1 to 0. */
+#  if defined (CASEMOD_CAPCASE)
+    name = string_extract (string, &t_index, "#%^,~:-=?+/}", SX_VARNAME);
+#  else
+    name = string_extract (string, &t_index, "#%^,:-=?+/}", SX_VARNAME);
+#  endif /* CASEMOD_CAPCASE */
+#else
+    name = string_extract (string, &t_index, "#%:-=?+/}", SX_VARNAME);
+#endif /* CASEMOD_EXPANSIONS */
+
+  ret = 0;
+  tflag = 0;
 
   /* If the name really consists of a special variable, then make sure
      that we have the entire name.  We don't allow indirect references
@@ -5456,6 +6399,13 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
     want_substring = 1;
   else if (c == '/' && string[sindex] != RBRACE)
     want_patsub = 1;
+#if defined (CASEMOD_EXPANSIONS)
+  else if (c == '^' || c == ',' || c == '~')
+    {
+      modspec = c;
+      want_casemod = 1;
+    }
+#endif
 
   /* Catch the valid and invalid brace expressions that made it through the
      tests above. */
@@ -5509,7 +6459,14 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       free (name);
 
       *indexp = sindex;
-      return ((number < 0) ? &expand_param_error : itos (number));
+      if (number < 0)
+        return (&expand_wdesc_error);
+      else
+       {
+         ret = alloc_word_desc ();
+         ret->word = itos (number);
+         return ret;
+       }
     }
 
   /* ${@} is identical to $@. */
@@ -5549,7 +6506,10 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       free (xlist);
       free (temp1);
       *indexp = sindex;
-      return (temp);
+
+      ret = alloc_word_desc ();
+      ret->word = temp;
+      return ret;
     }
 
 #if defined (ARRAY_VARS)      
@@ -5564,7 +6524,7 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       FREE (x);
       if (ALL_ELEMENT_SUB (x1[0]) && x1[1] == ']')
        {
-         temp = array_keys (temp1, quoted);
+         temp = array_keys (temp1, quoted);    /* handles assoc vars too */
          if (x1[0] == '@')
            {
              if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
@@ -5575,7 +6535,10 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
 
          free (temp1);
          *indexp = sindex;
-         return (temp);
+
+         ret = alloc_word_desc ();
+         ret->word = temp;
+         return ret;
        }
 
       free (temp1);
@@ -5591,9 +6554,18 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
     }
 
   if (want_indir)
-    temp = parameter_brace_expand_indir (name + 1, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at);
+    tdesc = parameter_brace_expand_indir (name + 1, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at);
+  else
+    tdesc = parameter_brace_expand_word (name, var_is_special, quoted);
+
+  if (tdesc)
+    {
+      temp = tdesc->word;
+      tflag = tdesc->flags;
+      dispose_word_desc (tdesc);
+    }
   else
-    temp = parameter_brace_expand_word (name, var_is_special, quoted);
+    temp = (char  *)0;
 
 #if defined (ARRAY_VARS)
   if (valid_array_reference (name))
@@ -5626,7 +6598,17 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       FREE (name);
       FREE (value);
       FREE (temp);
-      return (temp1);
+
+      if (temp1 == &expand_param_error)
+       return (&expand_wdesc_error);
+      else if (temp1 == &expand_param_fatal)
+       return (&expand_wdesc_fatal);
+
+      ret = alloc_word_desc ();
+      ret->word = temp1;
+      if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
+       ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
+      return ret;
     }
   else if (want_patsub)
     {
@@ -5634,8 +6616,40 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       FREE (name);
       FREE (value);
       FREE (temp);
-      return (temp1);
+
+      if (temp1 == &expand_param_error)
+       return (&expand_wdesc_error);
+      else if (temp1 == &expand_param_fatal)
+       return (&expand_wdesc_fatal);
+
+      ret = alloc_word_desc ();
+      ret->word = temp1;
+      ret = alloc_word_desc ();
+      ret->word = temp1;
+      if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
+       ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
+      return ret;
+    }
+#if defined (CASEMOD_EXPANSIONS)
+  else if (want_casemod)
+    {
+      temp1 = parameter_brace_casemod (name, temp, modspec, value, quoted);
+      FREE (name);
+      FREE (value);
+      FREE (temp);
+
+      if (temp1 == &expand_param_error)
+       return (&expand_wdesc_error);
+      else if (temp1 == &expand_param_fatal)
+       return (&expand_wdesc_fatal);
+
+      ret = alloc_word_desc ();
+      ret->word = temp1;
+      if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
+       ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
+      return ret;
     }
+#endif
 
   /* Do the right thing based on which character ended the variable name. */
   switch (c)
@@ -5647,7 +6661,7 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       FREE (value);
       FREE (temp);
       free (name);
-      return &expand_param_error;
+      return &expand_wdesc_error;
 
     case RBRACE:
       if (var_is_set == 0 && unbound_vars_is_error)
@@ -5657,7 +6671,7 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
          FREE (temp);
          free (name);
          last_command_exit_value = EXECUTION_FAILURE;
-         return (interactive_shell ? &expand_param_error : &expand_param_fatal);
+         return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
        }
       break;
 
@@ -5671,8 +6685,12 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       temp1 = parameter_brace_remove_pattern (name, temp, value, c, quoted);
       free (temp);
       free (value);
-      temp = temp1;
-      break;
+
+      ret = alloc_word_desc ();
+      ret->word = temp1;
+      if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
+       ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
+      return ret;
 
     case '-':
     case '=':
@@ -5696,10 +6714,12 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
              FREE (temp);
              if (value)
                {
-                 temp = parameter_brace_expand_rhs (name, value, c,
-                                                    quoted,
-                                                    quoted_dollar_atp,
-                                                    contains_dollar_at);
+                 ret = parameter_brace_expand_rhs (name, value, c,
+                                                   quoted,
+                                                   quoted_dollar_atp,
+                                                   contains_dollar_at);
+                 /* XXX - fix up later, esp. noting presence of
+                          W_HASQUOTEDNULL in ret->flags */
                  free (value);
                }
              else
@@ -5720,12 +6740,12 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
              report_error (_("$%s: cannot assign in this way"), name);
              free (name);
              free (value);
-             return &expand_param_error;
+             return &expand_wdesc_error;
            }
          else if (c == '?')
            {
              parameter_brace_expand_error (name, value);
-             return (interactive_shell ? &expand_param_error : &expand_param_fatal);
+             return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
            }
          else if (c != '+')
            {
@@ -5737,9 +6757,11 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
              if (contains_dollar_at)
                *contains_dollar_at = 0;
 
-             temp = parameter_brace_expand_rhs (name, value, c, quoted,
-                                                quoted_dollar_atp,
-                                                contains_dollar_at);
+             ret = parameter_brace_expand_rhs (name, value, c, quoted,
+                                               quoted_dollar_atp,
+                                               contains_dollar_at);
+             /* XXX - fix up later, esp. noting presence of
+                      W_HASQUOTEDNULL in tdesc->flags */
            }
          free (value);
        }
@@ -5747,13 +6769,20 @@ parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_doll
       break;
     }
   free (name);
-  return (temp);
+
+  if (ret == 0)
+    {
+      ret = alloc_word_desc ();
+      ret->flags = tflag;
+      ret->word = temp;
+    }
+  return (ret);
 }
 
 /* Expand a single ${xxx} expansion.  The braces are optional.  When
    the braces are used, parameter_brace_expand() does the work,
    possibly calling param_expand recursively. */
-static char *
+static WORD_DESC *
 param_expand (string, sindex, quoted, expanded_something,
              contains_dollar_at, quoted_dollar_at_p, had_quoted_null_p,
              pflags)
@@ -5767,11 +6796,15 @@ param_expand (string, sindex, quoted, expanded_something,
   intmax_t number;
   SHELL_VAR *var;
   WORD_LIST *list;
+  WORD_DESC *tdesc, *ret;
+  int tflag;
 
   zindex = *sindex;
   c = string[++zindex];
 
   temp = (char *)NULL;
+  ret = tdesc = (WORD_DESC *)NULL;
+  tflag = 0;
 
   /* Do simple cases first. Switch on what follows '$'. */
   switch (c)
@@ -5795,18 +6828,15 @@ param_expand (string, sindex, quoted, expanded_something,
          uerror[2] = '\0';
          err_unboundvar (uerror);
          last_command_exit_value = EXECUTION_FAILURE;
-         return (interactive_shell ? &expand_param_error : &expand_param_fatal);
+         return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
        }
-#if 1
       if (temp1)
        temp = (*temp1 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
                  ? quote_string (temp1)
                  : quote_escapes (temp1);
       else
        temp = (char *)NULL;
-#else
-      temp = temp1 ? quote_escapes (temp1) : (char *)NULL;
-#endif
+
       break;
 
     /* $$ -- pid of the invoking shell. */
@@ -5846,7 +6876,7 @@ param_expand (string, sindex, quoted, expanded_something,
              uerror[2] = '\0';
              err_unboundvar (uerror);
              last_command_exit_value = EXECUTION_FAILURE;
-             return (interactive_shell ? &expand_param_error : &expand_param_fatal);
+             return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
            }
        }
       else
@@ -5857,6 +6887,16 @@ param_expand (string, sindex, quoted, expanded_something,
     case '*':          /* `$*' */
       list = list_rest_of_args ();
 
+      if (list == 0 && unbound_vars_is_error)
+       {
+         uerror[0] = '$';
+         uerror[1] = '*';
+         uerror[2] = '\0';
+         err_unboundvar (uerror);
+         last_command_exit_value = EXECUTION_FAILURE;
+         return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
+       }
+
       /* If there are no command-line arguments, this should just
         disappear if there are other characters in the expansion,
         even if it's quoted. */
@@ -5869,19 +6909,32 @@ param_expand (string, sindex, quoted, expanded_something,
             quote the whole string, including the separators.  If IFS
             is unset, the parameters are separated by ' '; if $IFS is
             null, the parameters are concatenated. */
-#if 0
-         temp = string_list_dollar_star (list);
-#else
          temp = (quoted & Q_DOUBLE_QUOTES) ? string_list_dollar_star (list) : string_list (list);
-#endif
          temp1 = quote_string (temp);
+         if (*temp == 0)
+           tflag |= W_HASQUOTEDNULL;
          free (temp);
          temp = temp1;
        }
       else
        {
-         /* If the $* is not quoted it is identical to $@ */
+         /* We check whether or not we're eventually going to split $* here,
+            for example when IFS is empty and we are processing the rhs of
+            an assignment statement.  In that case, we don't separate the
+            arguments at all.  Otherwise, if the $* is not quoted it is
+            identical to $@ */
+#if 1
+#  if defined (HANDLE_MULTIBYTE)
+         if (expand_no_split_dollar_star && ifs_firstc[0] == 0)
+#  else
+         if (expand_no_split_dollar_star && ifs_firstc == 0)
+#  endif
+           temp = string_list_dollar_star (list);
+         else
+           temp = string_list_dollar_at (list, quoted);
+#else
          temp = string_list_dollar_at (list, quoted);
+#endif
          if (expand_no_split_dollar_star == 0 && contains_dollar_at)
            *contains_dollar_at = 1;
        }
@@ -5896,6 +6949,16 @@ param_expand (string, sindex, quoted, expanded_something,
     case '@':          /* `$@' */
       list = list_rest_of_args ();
 
+      if (list == 0 && unbound_vars_is_error)
+       {
+         uerror[0] = '$';
+         uerror[1] = '@';
+         uerror[2] = '\0';
+         err_unboundvar (uerror);
+         last_command_exit_value = EXECUTION_FAILURE;
+         return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
+       }
+
       /* We want to flag the fact that we saw this.  We can't turn
         off quoting entirely, because other characters in the
         string might need it (consider "\"$@\""), but we need some
@@ -5917,11 +6980,13 @@ param_expand (string, sindex, quoted, expanded_something,
       break;
 
     case LBRACE:
-      temp = parameter_brace_expand (string, &zindex, quoted,
-                                    quoted_dollar_at_p,
-                                    contains_dollar_at);
-      if (temp == &expand_param_error || temp == &expand_param_fatal)
-       return (temp);
+      tdesc = parameter_brace_expand (string, &zindex, quoted,
+                                     quoted_dollar_at_p,
+                                     contains_dollar_at);
+
+      if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
+       return (tdesc);
+      temp = tdesc ? tdesc->word : (char *)0;
 
       /* XXX */
       /* Quoted nulls should be removed if there is anything else
@@ -5931,25 +6996,26 @@ param_expand (string, sindex, quoted, expanded_something,
         in the string, discard TEMP, and go on.  The exception to
         this is when we have "${@}" and $1 is '', since $@ needs
         special handling. */
-      if (temp && QUOTED_NULL (temp))
+      if (tdesc && tdesc->word && (tdesc->flags & W_HASQUOTEDNULL) && QUOTED_NULL (temp))
        {
          if (had_quoted_null_p)
            *had_quoted_null_p = 1;
          if (*quoted_dollar_at_p == 0)
            {
              free (temp);
-             temp = (char *)NULL;
+             tdesc->word = temp = (char *)NULL;
            }
            
        }
 
+      ret = tdesc;
       goto return0;
 
     /* Do command or arithmetic substitution. */
     case LPAREN:
       /* We have to extract the contents of this paren substitution. */
       t_index = zindex + 1;
-      temp = extract_command_subst (string, &t_index);
+      temp = extract_command_subst (string, &t_index, 0);
       zindex = t_index;
 
       /* For Posix.2-style `$(( ))' arithmetic substitution,
@@ -5970,8 +7036,14 @@ param_expand (string, sindex, quoted, expanded_something,
          /* Cut off ending `)' */
          temp2[t_index] = '\0';
 
+         if (chk_arithsub (temp2, t_index) == 0)
+           {
+             free (temp2);
+             goto comsub;
+           }
+
          /* Expand variables found inside the expression. */
-         temp1 = expand_string_if_necessary (temp2, Q_DOUBLE_QUOTES, expand_string);
+         temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES);
          free (temp2);
 
 arithsub:
@@ -5985,10 +7057,10 @@ arithsub:
              if (interactive_shell == 0 && posixly_correct)
                {
                  last_command_exit_value = EXECUTION_FAILURE;
-                 return (&expand_param_fatal);
+                 return (&expand_wdesc_fatal);
                }
              else
-               return (&expand_param_error);
+               return (&expand_wdesc_error);
            }
          temp = itos (number);
          break;
@@ -5999,7 +7071,12 @@ comsub:
        /* we need zindex+1 because string[zindex] == RPAREN */
        temp1 = substring (string, *sindex, zindex+1);
       else
-       temp1 = command_substitute (temp, quoted);
+       {
+         tdesc = command_substitute (temp, quoted);
+         temp1 = tdesc ? tdesc->word : (char *)NULL;
+         if (tdesc)
+           dispose_word_desc (tdesc);
+       }
       FREE (temp);
       temp = temp1;
       break;
@@ -6011,9 +7088,16 @@ comsub:
       t_index = zindex + 1;
       temp = extract_arithmetic_subst (string, &t_index);
       zindex = t_index;
+      if (temp == 0)
+       {
+         temp = savestring (string);
+         if (expanded_something)
+           *expanded_something = 0;
+         goto return0;
+       }         
 
        /* Do initial variable expansion. */
-      temp1 = expand_string_if_necessary (temp, Q_DOUBLE_QUOTES, expand_string);
+      temp1 = expand_arith_string (temp, Q_DOUBLE_QUOTES);
 
       goto arithsub;
 
@@ -6043,9 +7127,10 @@ comsub:
       if (var && invisible_p (var) == 0 && var_isset (var))
        {
 #if defined (ARRAY_VARS)
-         if (array_p (var))
+         if (assoc_p (var) || array_p (var))
            {
-             temp = array_reference (array_cell (var), 0);
+             temp = array_p (var) ? array_reference (array_cell (var), 0)
+                                  : assoc_reference (assoc_cell (var), "0");
              if (temp)
                temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
                          ? quote_string (temp)
@@ -6082,8 +7167,8 @@ unbound_variable:
       free (temp1);
       last_command_exit_value = EXECUTION_FAILURE;
       return ((unbound_vars_is_error && interactive_shell == 0)
-               ? &expand_param_fatal
-               : &expand_param_error);
+               ? &expand_wdesc_fatal
+               : &expand_wdesc_error);
     }
 
   if (string[zindex])
@@ -6091,7 +7176,14 @@ unbound_variable:
 
 return0:
   *sindex = zindex;
-  return (temp);
+
+  if (ret == 0)
+    {
+      ret = alloc_word_desc ();
+      ret->flags = tflag;      /* XXX */
+      ret->word = temp;
+    }
+  return ret;
 }
 
 /* Make a word list which is the result of parameter and variable
@@ -6159,10 +7251,13 @@ expand_word_internal (word, quoted, isexp, contains_dollar_at, expanded_somethin
      string (e.g., "xx"ab), or is fully quoted (e.g., "xxab"). */
   int quoted_state;
 
+  /* State flags */
   int had_quoted_null;
   int has_dollar_at;
   int tflag;
 
+  int assignoff;               /* If assignment, offset of `=' */
+
   register unsigned char c;    /* Current character. */
   int t_index;                 /* For calls to string_extract_xxx. */
 
@@ -6178,11 +7273,15 @@ expand_word_internal (word, quoted, isexp, contains_dollar_at, expanded_somethin
   string = word->word;
   if (string == 0)
     goto finished_with_string;
-  string_size = strlen (string);
+  /* Don't need the string length for the SADD... and COPY_ macros unless
+     multibyte characters are possible. */
+  string_size = (MB_CUR_MAX > 1) ? strlen (string) : 1;
 
   if (contains_dollar_at)
     *contains_dollar_at = 0;
 
+  assignoff = -1;
+
   /* Begin the expansion. */
 
   for (sindex = 0; ;)
@@ -6229,7 +7328,7 @@ add_string:
        case '<':
        case '>':
          {
-           if (string[++sindex] != LPAREN || (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || posixly_correct)
+           if (string[++sindex] != LPAREN || (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (word->flags & (W_DQUOTE|W_NOPROCSUB)) || posixly_correct)
              {
                sindex--;       /* add_character: label increments sindex */
                goto add_character;
@@ -6252,25 +7351,114 @@ add_string:
          }
 #endif /* PROCESS_SUBSTITUTION */
 
+       case '=':
+         /* Posix.2 section 3.6.1 says that tildes following `=' in words
+            which are not assignment statements are not expanded.  If the
+            shell isn't in posix mode, though, we perform tilde expansion
+            on `likely candidate' unquoted assignment statements (flags
+            include W_ASSIGNMENT but not W_QUOTED).  A likely candidate
+            contains an unquoted :~ or =~.  Something to think about: we
+            now have a flag that says  to perform tilde expansion on arguments
+            to `assignment builtins' like declare and export that look like
+            assignment statements.  We now do tilde expansion on such words
+            even in POSIX mode. */     
+         if (word->flags & (W_ASSIGNRHS|W_NOTILDE))
+           goto add_character;
+         /* If we're not in posix mode or forcing assignment-statement tilde
+            expansion, note where the `=' appears in the word and prepare to
+            do tilde expansion following the first `='. */
+         if ((word->flags & W_ASSIGNMENT) &&
+             (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
+             assignoff == -1 && sindex > 0)
+           assignoff = sindex;
+         if (sindex == assignoff && string[sindex+1] == '~')   /* XXX */
+           word->flags |= W_ITILDE;
+#if 0
+         else if ((word->flags & W_ASSIGNMENT) &&
+                  (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
+                  string[sindex+1] == '~')
+           word->flags |= W_ITILDE;
+#endif
+         goto add_character;
+
+       case ':':
+         if (word->flags & W_NOTILDE)
+           goto add_character;
+
+         if ((word->flags & (W_ASSIGNMENT|W_ASSIGNRHS|W_TILDEEXP)) &&
+             string[sindex+1] == '~')
+           word->flags |= W_ITILDE;
+         goto add_character;
+
+       case '~':
+         /* If the word isn't supposed to be tilde expanded, or we're not
+            at the start of a word or after an unquoted : or = in an
+            assignment statement, we don't do tilde expansion. */
+         if ((word->flags & (W_NOTILDE|W_DQUOTE)) ||
+             (sindex > 0 && ((word->flags & W_ITILDE) == 0)) ||
+             (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
+           {
+             word->flags &= ~W_ITILDE;
+             goto add_character;
+           }
+
+         if (word->flags & W_ASSIGNRHS)
+           tflag = 2;
+         else if (word->flags & (W_ASSIGNMENT|W_TILDEEXP))
+           tflag = 1;
+         else
+           tflag = 0;
+
+         temp = bash_tilde_find_word (string + sindex, tflag, &t_index);
+           
+         word->flags &= ~W_ITILDE;
+
+         if (temp && *temp && t_index > 0)
+           {
+             temp1 = bash_tilde_expand (temp, tflag);
+             if  (temp1 && *temp1 == '~' && STREQ (temp, temp1))
+               {
+                 FREE (temp);
+                 FREE (temp1);
+                 goto add_character;           /* tilde expansion failed */
+               }
+             free (temp);
+             temp = temp1;
+             sindex += t_index;
+             goto add_quoted_string;           /* XXX was add_string */
+           }
+         else
+           {
+             FREE (temp);
+             goto add_character;
+           }
+       
        case '$':
          if (expanded_something)
            *expanded_something = 1;
 
          has_dollar_at = 0;
-         temp = param_expand (string, &sindex, quoted, expanded_something,
+         tword = param_expand (string, &sindex, quoted, expanded_something,
                               &has_dollar_at, &quoted_dollar_at,
                               &had_quoted_null,
                               (word->flags & W_NOCOMSUB) ? PF_NOCOMSUB : 0);
 
-         if (temp == &expand_param_error || temp == &expand_param_fatal)
+         if (tword == &expand_wdesc_error || tword == &expand_wdesc_fatal)
            {
              free (string);
              free (istring);
-             return ((temp == &expand_param_error) ? &expand_word_error
-                                                   : &expand_word_fatal);
+             return ((tword == &expand_wdesc_error) ? &expand_word_error
+                                                    : &expand_word_fatal);
            }
          if (contains_dollar_at && has_dollar_at)
            *contains_dollar_at = 1;
+
+         if (tword && (tword->flags & W_HASQUOTEDNULL))
+           had_quoted_null = 1;
+
+         temp = tword->word;
+         dispose_word_desc (tword);
+
          goto add_string;
          break;
 
@@ -6278,17 +7466,36 @@ add_string:
          {
            t_index = sindex++;
 
+           temp = string_extract (string, &sindex, "`", SX_REQMATCH);
+           /* The test of sindex against t_index is to allow bare instances of
+              ` to pass through, for backwards compatibility. */
+           if (temp == &extract_string_error || temp == &extract_string_fatal)
+             {
+               if (sindex - 1 == t_index)
+                 {
+                   sindex = t_index;
+                   goto add_character;
+                 }
+               report_error (_("bad substitution: no closing \"`\" in %s") , string+t_index);
+               free (string);
+               free (istring);
+               return ((temp == &extract_string_error) ? &expand_word_error
+                                                       : &expand_word_fatal);
+             }
+               
            if (expanded_something)
              *expanded_something = 1;
 
-           temp = string_extract (string, &sindex, "`", 0);
            if (word->flags & W_NOCOMSUB)
              /* sindex + 1 because string[sindex] == '`' */
              temp1 = substring (string, t_index, sindex + 1);
            else
              {
                de_backslash (temp);
-               temp1 = command_substitute (temp, quoted);
+               tword = command_substitute (temp, quoted);
+               temp1 = tword ? tword->word : (char *)NULL;
+               if (tword)
+                 dispose_word_desc (tword);
              }
            FREE (temp);
            temp = temp1;
@@ -6339,9 +7546,9 @@ add_twochars:
 
        case '"':
 #if 0
-         if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT|Q_PATQUOTE))
+         if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (word->flags & W_DQUOTE))
 #else
-         if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
+         if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
 #endif
            goto add_character;
 
@@ -6356,11 +7563,13 @@ add_twochars:
 
          if (temp && *temp)
            {
-             tword = make_word (temp);         /* XXX */
-             free (temp);
+             tword = alloc_word_desc ();
+             tword->word = temp;
+
              temp = (char *)NULL;
 
              has_dollar_at = 0;
+             /* Need to get W_HASQUOTEDNULL flag through this function. */
              list = expand_word_internal (tword, Q_DOUBLE_QUOTES, 0, &has_dollar_at, (int *)NULL);
 
              if (list == &expand_word_error || list == &expand_word_fatal)
@@ -6396,6 +7605,9 @@ add_twochars:
              if (list)
                dequote_list (list);
 
+             if (list && list->word && (list->word->flags & W_HASQUOTEDNULL))
+               had_quoted_null = 1;
+
              if (has_dollar_at)
                {
                  quoted_dollar_at++;
@@ -6435,8 +7647,9 @@ add_twochars:
              else
                {
                  temp = savestring (list->word->word);
+                 tflag = list->word->flags;
                  dispose_words (list);
-#if 1
+
                  /* If the string is not a quoted null string, we want
                     to remove any embedded unquoted CTLNUL characters.
                     We do not want to turn quoted null strings back into
@@ -6445,15 +7658,13 @@ add_twochars:
                     contain other characters.  For example, if we have
                     x"$*"y or "x$*y" and there are no positional parameters,
                     the $* should expand into nothing. */
-                 /* HOWEVER, this fails if the string contains a literal
-                    CTLNUL or CTLNUL is contained in the (non-null) expansion
-                    of some variable.  I'm not sure what to do about this
-                    yet.  There has to be some way to indicate the difference
-                    between the two.  An auxiliary data structure might be
-                    necessary. */
-                 if (QUOTED_NULL (temp) == 0)
+                 /* We use the W_HASQUOTEDNULL flag to differentiate the
+                    cases:  a quoted null character as above and when
+                    CTLNUL is contained in the (non-null) expansion
+                    of some variable.  We use the had_quoted_null flag to
+                    pass the value through this function to its caller. */
+                 if ((tflag & W_HASQUOTEDNULL) && QUOTED_NULL (temp) == 0)
                    remove_quoted_nulls (temp); /* XXX */
-#endif
                }
            }
          else
@@ -6485,9 +7696,9 @@ add_twochars:
 
        case '\'':
 #if 0
-         if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT|Q_PATQUOTE))
+         if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (word->flags & W_DQUOTE))
 #else
-         if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
+         if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
 #endif
            goto add_character;
 
@@ -6604,6 +7815,7 @@ finished_with_string:
          istring[0] = CTLNUL;
          istring[1] = '\0';
          tword = make_bare_word (istring);
+         tword->flags |= W_HASQUOTEDNULL;              /* XXX */
          list = make_word_list (tword, (WORD_LIST *)NULL);
          if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
            tword->flags |= W_QUOTED;
@@ -6617,9 +7829,9 @@ finished_with_string:
       else
        {
          tword = make_bare_word (istring);
-         list = make_word_list (tword, (WORD_LIST *)NULL);
          if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
            tword->flags |= W_QUOTED;
+         list = make_word_list (tword, (WORD_LIST *)NULL);
        }
 #else
       else
@@ -6629,13 +7841,19 @@ finished_with_string:
   else if (word->flags & W_NOSPLIT)
     {
       tword = make_bare_word (istring);
-      list = make_word_list (tword, (WORD_LIST *)NULL);
       if (word->flags & W_ASSIGNMENT)
        tword->flags |= W_ASSIGNMENT;   /* XXX */
+      if (word->flags & W_COMPASSIGN)
+       tword->flags |= W_COMPASSIGN;   /* XXX */
       if (word->flags & W_NOGLOB)
        tword->flags |= W_NOGLOB;       /* XXX */
+      if (word->flags & W_NOEXPAND)
+       tword->flags |= W_NOEXPAND;     /* XXX */
       if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
        tword->flags |= W_QUOTED;
+      if (had_quoted_null)
+       tword->flags |= W_HASQUOTEDNULL;
+      list = make_word_list (tword, (WORD_LIST *)NULL);
     }
   else
     {
@@ -6654,13 +7872,19 @@ finished_with_string:
       else
        {
          tword = make_bare_word (istring);
-         list = make_word_list (tword, (WORD_LIST *)NULL);
          if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (quoted_state == WHOLLY_QUOTED))
            tword->flags |= W_QUOTED;
          if (word->flags & W_ASSIGNMENT)
            tword->flags |= W_ASSIGNMENT;
+         if (word->flags & W_COMPASSIGN)
+           tword->flags |= W_COMPASSIGN;
          if (word->flags & W_NOGLOB)
            tword->flags |= W_NOGLOB;
+         if (word->flags & W_NOEXPAND)
+           tword->flags |= W_NOEXPAND;
+         if (had_quoted_null)
+           tword->flags |= W_HASQUOTEDNULL;    /* XXX */
+         list = make_word_list (tword, (WORD_LIST *)NULL);
        }
     }
 
@@ -6699,6 +7923,11 @@ string_quote_removal (string, quoted)
        {
        case '\\':
          c = string[++sindex];
+         if (c == 0)
+           {
+             *r++ = '\\';
+             break;
+           }
          if (((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote) && (sh_syntaxtab[c] & CBSDQUOTE) == 0)
            *r++ = '\\';
          /* FALLTHROUGH */
@@ -6748,8 +7977,8 @@ word_quote_removal (word, quoted)
   char *t;
 
   t = string_quote_removal (word->word, quoted);
-  w = make_bare_word (t);
-  free (t);
+  w = alloc_word_desc ();
+  w->word = t ? t : savestring ("");
   return (w);
 }
 
@@ -6761,12 +7990,23 @@ word_list_quote_removal (list, quoted)
      WORD_LIST *list;
      int quoted;
 {
-  WORD_LIST *result, *t, *tresult;
+  WORD_LIST *result, *t, *tresult, *e;
 
   for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
     {
       tresult = make_word_list (word_quote_removal (t->word, quoted), (WORD_LIST *)NULL);
+#if 0
       result = (WORD_LIST *) list_append (result, tresult);
+#else
+      if (result == 0)
+       result = e = tresult;
+      else
+       {
+         e->next = tresult;
+         while (e->next)
+           e = e->next;
+       }
+#endif
     }
   return (result);
 }
@@ -6786,9 +8026,10 @@ setifs (v)
   unsigned char uc;
 
   ifs_var = v;
-  ifs_value = v ? value_cell (v) : " \t\n";
+  ifs_value = (v && value_cell (v)) ? value_cell (v) : " \t\n";
 
-  /* Should really merge ifs_cmap with sh_syntaxtab. */
+  /* Should really merge ifs_cmap with sh_syntaxtab.  XXX - doesn't yet
+     handle multibyte chars in IFS */
   memset (ifs_cmap, '\0', sizeof (ifs_cmap));
   for (t = ifs_value ; t && *t; t++)
     {
@@ -6796,7 +8037,29 @@ setifs (v)
       ifs_cmap[uc] = 1;
     }
 
+#if defined (HANDLE_MULTIBYTE)
+  if (ifs_value == 0)
+    {
+      ifs_firstc[0] = '\0';
+      ifs_firstc_len = 1;
+    }
+  else
+    {
+      size_t ifs_len;
+      ifs_len = strnlen (ifs_value, MB_CUR_MAX);
+      ifs_firstc_len = MBLEN (ifs_value, ifs_len);
+      if (ifs_firstc_len == 1 || ifs_firstc_len == 0 || MB_INVALIDCH (ifs_firstc_len))
+       {
+         ifs_firstc[0] = ifs_value[0];
+         ifs_firstc[1] = '\0';
+         ifs_firstc_len = 1;
+       }
+      else
+       memcpy (ifs_firstc, ifs_value, ifs_firstc_len);
+    }
+#else
   ifs_firstc = ifs_value ? *ifs_value : 0;
+#endif
 }
 
 char *
@@ -6834,12 +8097,19 @@ static WORD_LIST *
 word_list_split (list)
      WORD_LIST *list;
 {
-  WORD_LIST *result, *t, *tresult;
+  WORD_LIST *result, *t, *tresult, *e;
 
   for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
     {
       tresult = word_split (t->word, ifs_value);
-      result = (WORD_LIST *) list_append (result, tresult);
+      if (result == 0)
+        result = e = tresult;
+      else
+       {
+         e->next = tresult;
+         while (e->next)
+           e = e->next;
+       }
     }
   return (result);
 }
@@ -6855,9 +8125,15 @@ static void
 exp_jump_to_top_level (v)
      int v;
 {
+  set_pipestatus_from_exit (last_command_exit_value);
+
   /* Cleanup code goes here. */
   expand_no_split_dollar_star = 0;     /* XXX */
   expanding_redir = 0;
+  assigning_in_environment = 0;
+
+  if (parse_and_execute_level == 0)
+    top_level_cleanup ();                      /* from sig.c */
 
   jump_to_top_level (v);
 }
@@ -7076,7 +8352,7 @@ glob_expand_word_list (tlist, eflags)
          else if (fail_glob_expansion != 0)
            {
              report_error (_("no match: %s"), tlist->word->word);
-             jump_to_top_level (DISCARD);
+             exp_jump_to_top_level (DISCARD);
            }
          else if (allow_null_glob_expansion == 0)
            {
@@ -7171,6 +8447,30 @@ brace_expand_word_list (tlist, eflags)
 }
 #endif
 
+#if defined (ARRAY_VARS)
+/* Take WORD, a compound associative array assignment, and internally run
+   'declare -A w', where W is the variable name portion of WORD. */
+static int
+make_internal_declare (word, option)
+     char *word;
+     char *option;
+{
+  int t;
+  WORD_LIST *wl;
+  WORD_DESC *w;
+
+  w = make_word (word);
+
+  t = assignment (w->word, 0);
+  w->word[t] = '\0';
+
+  wl = make_word_list (w, (WORD_LIST *)NULL);
+  wl = make_word_list (make_word (option), wl);
+
+  return (declare_builtin (wl));  
+}  
+#endif
+
 static WORD_LIST *
 shell_expand_word_list (tlist, eflags)
      WORD_LIST *tlist;
@@ -7188,28 +8488,33 @@ shell_expand_word_list (tlist, eflags)
 
       next = tlist->next;
 
-      /* Posix.2 section 3.6.1 says that tildes following `=' in words
-        which are not assignment statements are not expanded.  If the
-        shell isn't in posix mode, though, we perform tilde expansion
-        on `likely candidate' unquoted assignment statements (flags
-        include W_ASSIGNMENT but not W_QUOTED).  A likely candidate
-        contains an unquoted :~ or =~.  Something to think about: we
-        now have a flag that says  to perform tilde expansion on arguments
-        to `assignment builtins' like declare and export that look like
-        assignment statements.  We now do tilde expansion on such words
-        even in POSIX mode. */
-      if (((tlist->word->flags & (W_ASSIGNMENT|W_QUOTED)) == W_ASSIGNMENT) &&
-            (posixly_correct == 0 || (tlist->word->flags & W_TILDEEXP)) &&
-            (unquoted_substring ("=~", temp_string) || unquoted_substring (":~", temp_string)))
-       {
-         tlist->word->word = bash_tilde_expand (temp_string, 1);
-         free (temp_string);
-       }
-      else if (temp_string[0] == '~')
+#if defined (ARRAY_VARS)
+      /* If this is a compound array assignment to a builtin that accepts
+         such assignments (e.g., `declare'), take the assignment and perform
+         it separately, handling the semantics of declarations inside shell
+         functions.  This avoids the double-evaluation of such arguments,
+         because `declare' does some evaluation of compound assignments on
+         its own. */
+      if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG))
        {
-         tlist->word->word = bash_tilde_expand (temp_string, 0);
-         free (temp_string);
+         int t;
+
+         if (tlist->word->flags & W_ASSIGNASSOC)
+           make_internal_declare (tlist->word->word, "-A");
+
+         t = do_word_assignment (tlist->word);
+         if (t == 0)
+           {
+             last_command_exit_value = EXECUTION_FAILURE;
+             exp_jump_to_top_level (DISCARD);
+           }
+
+         /* Now transform the word as ksh93 appears to do and go on */
+         t = assignment (tlist->word->word, 0);
+         tlist->word->word[t] = '\0';
+         tlist->word->flags &= ~(W_ASSIGNMENT|W_NOSPLIT|W_COMPASSIGN|W_ASSIGNARG|W_ASSIGNASSOC);
        }
+#endif
 
       expanded_something = 0;
       expanded = expand_word_internal
@@ -7297,7 +8602,7 @@ expand_word_list_internal (list, eflags)
              for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
                {
                  this_command_name = (char *)NULL;     /* no arithmetic errors */
-                 tint = do_assignment (temp_list->word->word);
+                 tint = do_word_assignment (temp_list->word);
                  /* Variable assignment errors in non-interactive shells
                     running in Posix.2 mode cause the shell to exit. */
                  if (tint == 0)
@@ -7345,23 +8650,25 @@ expand_word_list_internal (list, eflags)
 
   if ((eflags & WEXP_VARASSIGN) && subst_assign_varlist)
     {
-      sh_assign_func_t *assign_func;
+      sh_wassign_func_t *assign_func;
 
       /* If the remainder of the words expand to nothing, Posix.2 requires
         that the variable and environment assignments affect the shell's
         environment. */
-      assign_func = new_list ? assign_in_env : do_assignment;
+      assign_func = new_list ? assign_in_env : do_word_assignment;
       tempenv_assign_error = 0;
 
       for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
        {
          this_command_name = (char *)NULL;
-         tint = (*assign_func) (temp_list->word->word);
+         assigning_in_environment = (assign_func == assign_in_env);
+         tint = (*assign_func) (temp_list->word);
+         assigning_in_environment = 0;
          /* Variable assignment errors in non-interactive shells running
             in Posix.2 mode cause the shell to exit. */
          if (tint == 0)
            {
-             if (assign_func == do_assignment)
+             if (assign_func == do_word_assignment)
                {
                  last_command_exit_value = EXECUTION_FAILURE;
                  if (interactive_shell == 0 && posixly_correct)