]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blobdiff - libiberty/d-demangle.c
Update year range in copyright notice of binutils files
[thirdparty/binutils-gdb.git] / libiberty / d-demangle.c
index 12457f003b11b66e466597f3ad55368c431d20c9..822c7580782742bba534328e6f8bfbf47df01a65 100644 (file)
@@ -1,5 +1,5 @@
 /* Demangler for the D programming language
-   Copyright (C) 2014-2017 Free Software Foundation, Inc.
+   Copyright (C) 2014-2021 Free Software Foundation, Inc.
    Written by Iain Buclaw (ibuclaw@gdcproject.org)
 
 This file is part of the libiberty library.
@@ -26,13 +26,14 @@ You should have received a copy of the GNU Library General Public
 License along with libiberty; see the file COPYING.LIB.
 If not, see <http://www.gnu.org/licenses/>.  */
 
-/* This file exports one function; dlang_demangle.
-
-   This file imports strtol for decoding mangled literals.  */
+/* This file exports one function; dlang_demangle.  */
 
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
 
 #include "safe-ctype.h"
 
@@ -42,13 +43,18 @@ If not, see <http://www.gnu.org/licenses/>.  */
 
 #ifdef HAVE_STDLIB_H
 #include <stdlib.h>
-#else
-extern long strtol (const char *nptr, char **endptr, int base);
 #endif
 
 #include <demangle.h>
 #include "libiberty.h"
 
+#ifndef ULONG_MAX
+#define        ULONG_MAX       (~0UL)
+#endif
+#ifndef UINT_MAX
+#define        UINT_MAX        (~0U)
+#endif
+
 /* A mini string-handling package */
 
 typedef struct string          /* Beware: these aren't required to be */
@@ -59,9 +65,9 @@ typedef struct string         /* Beware: these aren't required to be */
 } string;
 
 static void
-string_need (string *s, int n)
+string_need (string *s, size_t n)
 {
-  int tem;
+  size_t tem;
 
   if (s->b == NULL)
     {
@@ -72,7 +78,7 @@ string_need (string *s, int n)
       s->p = s->b = XNEWVEC (char, n);
       s->e = s->b + n;
     }
-  else if (s->e - s->p < n)
+  else if ((size_t) (s->e - s->p) < n)
     {
       tem = s->p - s->b;
       n += tem;
@@ -121,14 +127,14 @@ string_setlength (string *s, int n)
 static void
 string_append (string *p, const char *s)
 {
-  int n = strlen (s);
+  size_t n = strlen (s);
   string_need (p, n);
   memcpy (p->p, s, n);
   p->p += n;
 }
 
 static void
-string_appendn (string *p, const char *s, int n)
+string_appendn (string *p, const char *s, size_t n)
 {
   if (n != 0)
     {
@@ -139,7 +145,7 @@ string_appendn (string *p, const char *s, int n)
 }
 
 static void
-string_prependn (string *p, const char *s, int n)
+string_prependn (string *p, const char *s, size_t n)
 {
   char *q;
 
@@ -164,35 +170,290 @@ string_prepend (string *p, const char *s)
     }
 }
 
-/* What kinds of symbol we could be parsing.  */
-enum dlang_symbol_kinds
+/* Demangle information structure we pass around.  */
+struct dlang_info
 {
-  /* Top-level symbol, needs it's type checked.  */
-  dlang_top_level,
-  /* Function symbol, needs it's type checked.   */
-  dlang_function,
-  /* Strongly typed name, such as for classes, structs and enums.  */
-  dlang_type_name,
-  /* Template identifier.  */
-  dlang_template_ident,
-  /* Template symbol parameter.  */
-  dlang_template_param
+  /* The string we are demangling.  */
+  const char *s;
+  /* The index of the last back reference.  */
+  int last_backref;
 };
 
+/* Pass as the LEN to dlang_parse_template if symbol length is not known.  */
+#define TEMPLATE_LENGTH_UNKNOWN (-1UL)
+
 /* Prototypes for forward referenced functions */
-static const char *dlang_function_args (string *, const char *);
+static const char *dlang_function_type (string *, const char *,
+                                       struct dlang_info *);
 
-static const char *dlang_type (string *, const char *);
+static const char *dlang_function_args (string *, const char *,
+                                       struct dlang_info *);
+
+static const char *dlang_type (string *, const char *, struct dlang_info *);
 
 static const char *dlang_value (string *, const char *, const char *, char);
 
-static const char *dlang_parse_symbol (string *, const char *,
-                                      enum dlang_symbol_kinds);
+static const char *dlang_parse_qualified (string *, const char *,
+                                         struct dlang_info *, int);
+
+static const char *dlang_parse_mangle (string *, const char *,
+                                      struct dlang_info *);
+
+static const char *dlang_parse_tuple (string *, const char *,
+                                     struct dlang_info *);
+
+static const char *dlang_parse_template (string *, const char *,
+                                        struct dlang_info *, unsigned long);
+
+static const char *dlang_lname (string *, const char *, unsigned long);
+
+
+/* Extract the number from MANGLED, and assign the result to RET.
+   Return the remaining string on success or NULL on failure.
+   A result larger than UINT_MAX is considered a failure.  */
+static const char *
+dlang_number (const char *mangled, unsigned long *ret)
+{
+  /* Return NULL if trying to extract something that isn't a digit.  */
+  if (mangled == NULL || !ISDIGIT (*mangled))
+    return NULL;
+
+  unsigned long val = 0;
+
+  while (ISDIGIT (*mangled))
+    {
+      unsigned long digit = mangled[0] - '0';
+
+      /* Check for overflow.  */
+      if (val > (UINT_MAX - digit) / 10)
+       return NULL;
+
+      val = val * 10 + digit;
+      mangled++;
+    }
+
+  if (*mangled == '\0')
+    return NULL;
+
+  *ret = val;
+  return mangled;
+}
+
+/* Extract the hex-digit from MANGLED, and assign the result to RET.
+   Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_hexdigit (const char *mangled, char *ret)
+{
+  char c;
+
+  /* Return NULL if trying to extract something that isn't a hexdigit.  */
+  if (mangled == NULL || !ISXDIGIT (mangled[0]) || !ISXDIGIT (mangled[1]))
+    return NULL;
+
+  c = mangled[0];
+  if (!ISDIGIT (c))
+    (*ret) = (c - (ISUPPER (c) ? 'A' : 'a') + 10);
+  else
+    (*ret) = (c - '0');
+
+  c = mangled[1];
+  if (!ISDIGIT (c))
+    (*ret) = (*ret << 4) | (c - (ISUPPER (c) ? 'A' : 'a') + 10);
+  else
+    (*ret) = (*ret << 4) | (c - '0');
+
+  mangled += 2;
+
+  return mangled;
+}
+
+/* Extract the function calling convention from MANGLED and
+   return 1 on success or 0 on failure.  */
+static int
+dlang_call_convention_p (const char *mangled)
+{
+  switch (*mangled)
+    {
+    case 'F': case 'U': case 'V':
+    case 'W': case 'R': case 'Y':
+      return 1;
+
+    default:
+      return 0;
+    }
+}
+
+/* Extract the back reference position from MANGLED, and assign the result
+   to RET.  Return the remaining string on success or NULL on failure.
+   A result <= 0 is a failure.  */
+static const char *
+dlang_decode_backref (const char *mangled, long *ret)
+{
+  /* Return NULL if trying to extract something that isn't a digit.  */
+  if (mangled == NULL || !ISALPHA (*mangled))
+    return NULL;
+
+  /* Any identifier or non-basic type that has been emitted to the mangled
+     symbol before will not be emitted again, but is referenced by a special
+     sequence encoding the relative position of the original occurrence in the
+     mangled symbol name.
+
+     Numbers in back references are encoded with base 26 by upper case letters
+     A-Z for higher digits but lower case letters a-z for the last digit.
+
+       NumberBackRef:
+           [a-z]
+           [A-Z] NumberBackRef
+           ^
+   */
+  unsigned long val = 0;
+
+  while (ISALPHA (*mangled))
+    {
+      /* Check for overflow.  */
+      if (val > (ULONG_MAX - 25) / 26)
+       break;
+
+      val *= 26;
+
+      if (mangled[0] >= 'a' && mangled[0] <= 'z')
+       {
+         val += mangled[0] - 'a';
+         if ((long) val <= 0)
+           break;
+         *ret = val;
+         return mangled + 1;
+       }
+
+      val += mangled[0] - 'A';
+      mangled++;
+    }
+
+  return NULL;
+}
+
+/* Extract the symbol pointed at by the back reference and assign the result
+   to RET.  Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_backref (const char *mangled, const char **ret, struct dlang_info *info)
+{
+  (*ret) = NULL;
+
+  if (mangled == NULL || *mangled != 'Q')
+    return NULL;
+
+  /* Position of 'Q'.  */
+  const char *qpos = mangled;
+  long refpos;
+  mangled++;
+
+  mangled = dlang_decode_backref (mangled, &refpos);
+  if (mangled == NULL)
+    return NULL;
+
+  if (refpos > qpos - info->s)
+    return NULL;
+
+  /* Set the position of the back reference.  */
+  (*ret) = qpos - refpos;
+
+  return mangled;
+}
+
+/* Demangle a back referenced symbol from MANGLED and append it to DECL.
+   Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_symbol_backref (string *decl, const char *mangled,
+                     struct dlang_info *info)
+{
+  /* An identifier back reference always points to a digit 0 to 9.
+
+       IdentifierBackRef:
+           Q NumberBackRef
+           ^
+   */
+  const char *backref;
+  unsigned long len;
+
+  /* Get position of the back reference.  */
+  mangled = dlang_backref (mangled, &backref, info);
+
+  /* Must point to a simple identifier.  */
+  backref = dlang_number (backref, &len);
+  if (backref == NULL)
+    return NULL;
+
+  backref = dlang_lname (decl, backref, len);
+  if (backref == NULL)
+    return NULL;
+
+  return mangled;
+}
+
+/* Demangle a back referenced type from MANGLED and append it to DECL.
+   IS_FUNCTION is 1 if the back referenced type is expected to be a function.
+   Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_type_backref (string *decl, const char *mangled, struct dlang_info *info,
+                   int is_function)
+{
+  /* A type back reference always points to a letter.
+
+       TypeBackRef:
+           Q NumberBackRef
+           ^
+   */
+  const char *backref;
+
+  /* If we appear to be moving backwards through the mangle string, then
+     bail as this may be a recursive back reference.  */
+  if (mangled - info->s >= info->last_backref)
+    return NULL;
+
+  int save_refpos = info->last_backref;
+  info->last_backref = mangled - info->s;
+
+  /* Get position of the back reference.  */
+  mangled = dlang_backref (mangled, &backref, info);
+
+  /* Must point to a type.  */
+  if (is_function)
+    backref = dlang_function_type (decl, backref, info);
+  else
+    backref = dlang_type (decl, backref, info);
+
+  info->last_backref = save_refpos;
+
+  if (backref == NULL)
+    return NULL;
+
+  return mangled;
+}
+
+/* Extract the beginning of a symbol name from MANGLED and
+   return 1 on success or 0 on failure.  */
+static int
+dlang_symbol_name_p (const char *mangled, struct dlang_info *info)
+{
+  long ret;
+  const char *qref = mangled;
 
-static const char *dlang_parse_tuple (string *, const char *);
+  if (ISDIGIT (*mangled))
+    return 1;
 
-static const char *dlang_parse_template (string *, const char *, long);
+  if (mangled[0] == '_' && mangled[1] == '_'
+      && (mangled[2] == 'T' || mangled[2] == 'U'))
+    return 1;
 
+  if (*mangled != 'Q')
+    return 0;
+
+  mangled = dlang_decode_backref (mangled + 1, &ret);
+  if (mangled == NULL || ret > qref - info->s)
+    return 0;
+
+  return ISDIGIT (qref[-ret]);
+}
 
 /* Demangle the calling convention from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
@@ -327,6 +588,14 @@ dlang_attributes (string *decl, const char *mangled)
          mangled++;
          string_append (decl, "return ");
          continue;
+       case 'l': /* scope */
+         mangled++;
+         string_append (decl, "scope ");
+         continue;
+       case 'm': /* @live */
+         mangled++;
+         string_append (decl, "@live ");
+         continue;
 
        default: /* unknown attribute */
          return NULL;
@@ -337,13 +606,39 @@ dlang_attributes (string *decl, const char *mangled)
   return mangled;
 }
 
+/* Demangle the function type from MANGLED without the return type.
+   The arguments are appended to ARGS, the calling convention is appended
+   to CALL and attributes are appended to ATTR.  Any of these can be NULL
+   to throw the information away.  Return the remaining string on success
+   or NULL on failure.  */
+static const char *
+dlang_function_type_noreturn (string *args, string *call, string *attr,
+                             const char *mangled, struct dlang_info *info)
+{
+  string dump;
+  string_init (&dump);
+
+  /* Skip over calling convention and attributes.  */
+  mangled = dlang_call_convention (call ? call : &dump, mangled);
+  mangled = dlang_attributes (attr ? attr : &dump, mangled);
+
+  if (args)
+    string_append (args, "(");
+
+  mangled = dlang_function_args (args ? args : &dump, mangled, info);
+  if (args)
+    string_append (args, ")");
+
+  string_delete (&dump);
+  return mangled;
+}
+
 /* Demangle the function type from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_function_type (string *decl, const char *mangled)
+dlang_function_type (string *decl, const char *mangled, struct dlang_info *info)
 {
   string attr, args, type;
-  size_t szattr, szargs, sztype;
 
   if (mangled == NULL || *mangled == '\0')
     return NULL;
@@ -358,27 +653,16 @@ dlang_function_type (string *decl, const char *mangled)
   string_init (&args);
   string_init (&type);
 
-  /* Function call convention.  */
-  mangled = dlang_call_convention (decl, mangled);
-
-  /* Function attributes.  */
-  mangled = dlang_attributes (&attr, mangled);
-  szattr = string_length (&attr);
-
-  /* Function arguments.  */
-  mangled = dlang_function_args (&args, mangled);
-  szargs = string_length (&args);
+  mangled = dlang_function_type_noreturn (&args, decl, &attr, mangled, info);
 
   /* Function return type.  */
-  mangled = dlang_type (&type, mangled);
-  sztype = string_length (&type);
+  mangled = dlang_type (&type, mangled, info);
 
   /* Append to decl in order. */
-  string_appendn (decl, type.b, sztype);
-  string_append (decl, "(");
-  string_appendn (decl, args.b, szargs);
-  string_append (decl, ") ");
-  string_appendn (decl, attr.b, szattr);
+  string_appendn (decl, type.b, string_length (&type));
+  string_appendn (decl, args.b, string_length (&args));
+  string_append (decl, " ");
+  string_appendn (decl, attr.b, string_length (&attr));
 
   string_delete (&attr);
   string_delete (&args);
@@ -389,7 +673,7 @@ dlang_function_type (string *decl, const char *mangled)
 /* Demangle the argument list from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_function_args (string *decl, const char *mangled)
+dlang_function_args (string *decl, const char *mangled, struct dlang_info *info)
 {
   size_t n = 0;
 
@@ -429,6 +713,15 @@ dlang_function_args (string *decl, const char *mangled)
 
       switch (*mangled)
        {
+       case 'I': /* in(T) */
+         mangled++;
+         string_append (decl, "in ");
+         if (*mangled == 'K') /* in ref(T) */
+           {
+             mangled++;
+             string_append (decl, "ref ");
+           }
+         break;
        case 'J': /* out(T) */
          mangled++;
          string_append (decl, "out ");
@@ -442,7 +735,7 @@ dlang_function_args (string *decl, const char *mangled)
          string_append (decl, "lazy ");
          break;
        }
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
     }
 
   return mangled;
@@ -451,7 +744,7 @@ dlang_function_args (string *decl, const char *mangled)
 /* Demangle the type from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_type (string *decl, const char *mangled)
+dlang_type (string *decl, const char *mangled, struct dlang_info *info)
 {
   if (mangled == NULL || *mangled == '\0')
     return NULL;
@@ -461,19 +754,19 @@ dlang_type (string *decl, const char *mangled)
     case 'O': /* shared(T) */
       mangled++;
       string_append (decl, "shared(");
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, ")");
       return mangled;
     case 'x': /* const(T) */
       mangled++;
       string_append (decl, "const(");
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, ")");
       return mangled;
     case 'y': /* immutable(T) */
       mangled++;
       string_append (decl, "immutable(");
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, ")");
       return mangled;
     case 'N':
@@ -482,7 +775,7 @@ dlang_type (string *decl, const char *mangled)
        {
          mangled++;
          string_append (decl, "inout(");
-         mangled = dlang_type (decl, mangled);
+         mangled = dlang_type (decl, mangled, info);
          string_append (decl, ")");
          return mangled;
        }
@@ -490,7 +783,7 @@ dlang_type (string *decl, const char *mangled)
        {
          mangled++;
          string_append (decl, "__vector(");
-         mangled = dlang_type (decl, mangled);
+         mangled = dlang_type (decl, mangled, info);
          string_append (decl, ")");
          return mangled;
        }
@@ -498,7 +791,7 @@ dlang_type (string *decl, const char *mangled)
        return NULL;
     case 'A': /* dynamic array (T[]) */
       mangled++;
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, "[]");
       return mangled;
     case 'G': /* static array (T[N]) */
@@ -513,7 +806,7 @@ dlang_type (string *decl, const char *mangled)
          num++;
          mangled++;
        }
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, "[");
       string_appendn (decl, numptr, num);
       string_append (decl, "]");
@@ -526,10 +819,10 @@ dlang_type (string *decl, const char *mangled)
       mangled++;
 
       string_init (&type);
-      mangled = dlang_type (&type, mangled);
+      mangled = dlang_type (&type, mangled, info);
       sztype = string_length (&type);
 
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
       string_append (decl, "[");
       string_appendn (decl, type.b, sztype);
       string_append (decl, "]");
@@ -539,25 +832,29 @@ dlang_type (string *decl, const char *mangled)
     }
     case 'P': /* pointer (T*) */
       mangled++;
-      /* Function pointer types don't include the trailing asterisk.  */
-      switch (*mangled)
+      if (!dlang_call_convention_p (mangled))
        {
-       case 'F': case 'U': case 'W':
-       case 'V': case 'R': case 'Y':
-         mangled = dlang_function_type (decl, mangled);
-         string_append (decl, "function");
+         mangled = dlang_type (decl, mangled, info);
+         string_append (decl, "*");
          return mangled;
        }
-      mangled = dlang_type (decl, mangled);
-      string_append (decl, "*");
+      /* Fall through */
+    case 'F': /* function T (D) */
+    case 'U': /* function T (C) */
+    case 'W': /* function T (Windows) */
+    case 'V': /* function T (Pascal) */
+    case 'R': /* function T (C++) */
+    case 'Y': /* function T (Objective-C) */
+      /* Function pointer types don't include the trailing asterisk.  */
+      mangled = dlang_function_type (decl, mangled, info);
+      string_append (decl, "function");
       return mangled;
-    case 'I': /* ident T */
     case 'C': /* class T */
     case 'S': /* struct T */
     case 'E': /* enum T */
     case 'T': /* typedef T */
       mangled++;
-      return dlang_parse_symbol (decl, mangled, dlang_type_name);
+      return dlang_parse_qualified (decl, mangled, info, 0);
     case 'D': /* delegate T */
     {
       string mods;
@@ -568,7 +865,12 @@ dlang_type (string *decl, const char *mangled)
       mangled = dlang_type_modifiers (&mods, mangled);
       szmods = string_length (&mods);
 
-      mangled = dlang_function_type (decl, mangled);
+      /* Back referenced function type.  */
+      if (*mangled == 'Q')
+       mangled = dlang_type_backref (decl, mangled, info, 1);
+      else
+       mangled = dlang_function_type (decl, mangled, info);
+
       string_append (decl, "delegate");
       string_appendn (decl, mods.b, szmods);
 
@@ -577,7 +879,7 @@ dlang_type (string *decl, const char *mangled)
     }
     case 'B': /* tuple T */
       mangled++;
-      return dlang_parse_tuple (decl, mangled);
+      return dlang_parse_tuple (decl, mangled, info);
 
     /* Basic types */
     case 'n':
@@ -691,6 +993,10 @@ dlang_type (string *decl, const char *mangled)
        }
       return NULL;
 
+    /* Back referenced type.  */
+    case 'Q':
+      return dlang_type_backref (decl, mangled, info, 0);
+
     default: /* unhandled */
       return NULL;
     }
@@ -699,163 +1005,127 @@ dlang_type (string *decl, const char *mangled)
 /* Extract the identifier from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_identifier (string *decl, const char *mangled,
-                 enum dlang_symbol_kinds kind)
+dlang_identifier (string *decl, const char *mangled, struct dlang_info *info)
 {
-  char *endptr;
-  long len;
+  unsigned long len;
 
   if (mangled == NULL || *mangled == '\0')
     return NULL;
 
-  len = strtol (mangled, &endptr, 10);
+  if (*mangled == 'Q')
+    return dlang_symbol_backref (decl, mangled, info);
 
-  if (endptr == NULL || len <= 0)
-    return NULL;
+  /* May be a template instance without a length prefix.  */
+  if (mangled[0] == '_' && mangled[1] == '_'
+      && (mangled[2] == 'T' || mangled[2] == 'U'))
+    return dlang_parse_template (decl, mangled, info, TEMPLATE_LENGTH_UNKNOWN);
 
-  /* In template parameter symbols, the first character of the mangled
-     name can be a digit.  This causes ambiguity issues because the
-     digits of the two numbers are adjacent.  */
-  if (kind == dlang_template_param)
-    {
-      long psize = len;
-      char *pend;
-      int saved = string_length (decl);
+  const char *endptr = dlang_number (mangled, &len);
 
-      /* Work backwards until a match is found.  */
-      for (pend = endptr; endptr != NULL; pend--)
-       {
-         mangled = pend;
+  if (endptr == NULL || len == 0)
+    return NULL;
 
-         /* Reached the beginning of the pointer to the name length,
-            try parsing the entire symbol.  */
-         if (psize == 0)
-           {
-             psize = len;
-             pend = endptr;
-             endptr = NULL;
-           }
+  if (strlen (endptr) < len)
+    return NULL;
 
-         /* Check whether template parameter is a function with a valid
-            return type or an untyped identifier.  */
-         if (ISDIGIT (*mangled))
-           mangled = dlang_parse_symbol (decl, mangled, dlang_template_ident);
-         else if (strncmp (mangled, "_D", 2) == 0)
-           {
-             mangled += 2;
-             mangled = dlang_parse_symbol (decl, mangled, dlang_function);
-           }
+  mangled = endptr;
 
-         /* Check for name length mismatch.  */
-         if (mangled && (mangled - pend) == psize)
-           return mangled;
+  /* May be a template instance with a length prefix.  */
+  if (len >= 5 && mangled[0] == '_' && mangled[1] == '_'
+      && (mangled[2] == 'T' || mangled[2] == 'U'))
+    return dlang_parse_template (decl, mangled, info, len);
 
-         psize /= 10;
-         string_setlength (decl, saved);
-       }
+  return dlang_lname (decl, mangled, len);
+}
 
-      /* No match on any combinations.  */
-      return NULL;
-    }
-  else
+/* Extract the plain identifier from MANGLED and prepend/append it to DECL
+   with special treatment for some magic compiler generted symbols.
+   Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_lname (string *decl, const char *mangled, unsigned long len)
+{
+  switch (len)
     {
-      if (strlen (endptr) < (size_t) len)
-       return NULL;
-
-      mangled = endptr;
-
-      /* May be a template instance.  */
-      if (len >= 5 && strncmp (mangled, "__T", 3) == 0)
+    case 6:
+      if (strncmp (mangled, "__ctor", len) == 0)
        {
-         /* Template symbol.  */
-         if (ISDIGIT (mangled[3]) && mangled[3] != '0')
-           return dlang_parse_template (decl, mangled, len);
-
-         return NULL;
+         /* Constructor symbol for a class/struct.  */
+         string_append (decl, "this");
+         mangled += len;
+         return mangled;
        }
-
-      switch (len)
+      else if (strncmp (mangled, "__dtor", len) == 0)
        {
-       case 6:
-         if (strncmp (mangled, "__ctor", len) == 0)
-           {
-             /* Constructor symbol for a class/struct.  */
-             string_append (decl, "this");
-             mangled += len;
-             return mangled;
-           }
-         else if (strncmp (mangled, "__dtor", len) == 0)
-           {
-             /* Destructor symbol for a class/struct.  */
-             string_append (decl, "~this");
-             mangled += len;
-             return mangled;
-           }
-         else if (strncmp (mangled, "__initZ", len+1) == 0)
-           {
-             /* The static initialiser for a given symbol.  */
-             string_append (decl, "init$");
-             mangled += len;
-             return mangled;
-           }
-         else if (strncmp (mangled, "__vtblZ", len+1) == 0)
-           {
-             /* The vtable symbol for a given class.  */
-             string_prepend (decl, "vtable for ");
-             string_setlength (decl, string_length (decl) - 1);
-             mangled += len;
-             return mangled;
-           }
-         break;
-
-       case 7:
-         if (strncmp (mangled, "__ClassZ", len+1) == 0)
-           {
-             /* The classinfo symbol for a given class.  */
-             string_prepend (decl, "ClassInfo for ");
-             string_setlength (decl, string_length (decl) - 1);
-             mangled += len;
-             return mangled;
-           }
-         break;
+         /* Destructor symbol for a class/struct.  */
+         string_append (decl, "~this");
+         mangled += len;
+         return mangled;
+       }
+      else if (strncmp (mangled, "__initZ", len + 1) == 0)
+       {
+         /* The static initialiser for a given symbol.  */
+         string_prepend (decl, "initializer for ");
+         string_setlength (decl, string_length (decl) - 1);
+         mangled += len;
+         return mangled;
+       }
+      else if (strncmp (mangled, "__vtblZ", len + 1) == 0)
+       {
+         /* The vtable symbol for a given class.  */
+         string_prepend (decl, "vtable for ");
+         string_setlength (decl, string_length (decl) - 1);
+         mangled += len;
+         return mangled;
+       }
+      break;
 
-       case 10:
-         if (strncmp (mangled, "__postblitMFZ", len+3) == 0)
-           {
-             /* Postblit symbol for a struct.  */
-             string_append (decl, "this(this)");
-             mangled += len + 3;
-             return mangled;
-           }
-         break;
+    case 7:
+      if (strncmp (mangled, "__ClassZ", len + 1) == 0)
+       {
+         /* The classinfo symbol for a given class.  */
+         string_prepend (decl, "ClassInfo for ");
+         string_setlength (decl, string_length (decl) - 1);
+         mangled += len;
+         return mangled;
+       }
+      break;
 
-       case 11:
-         if (strncmp (mangled, "__InterfaceZ", len+1) == 0)
-           {
-             /* The interface symbol for a given class.  */
-             string_prepend (decl, "Interface for ");
-             string_setlength (decl, string_length (decl) - 1);
-             mangled += len;
-             return mangled;
-           }
-         break;
+    case 10:
+      if (strncmp (mangled, "__postblitMFZ", len + 3) == 0)
+       {
+         /* Postblit symbol for a struct.  */
+         string_append (decl, "this(this)");
+         mangled += len + 3;
+         return mangled;
+       }
+      break;
 
-       case 12:
-         if (strncmp (mangled, "__ModuleInfoZ", len+1) == 0)
-           {
-             /* The ModuleInfo symbol for a given module.  */
-             string_prepend (decl, "ModuleInfo for ");
-             string_setlength (decl, string_length (decl) - 1);
-             mangled += len;
-             return mangled;
-           }
-         break;
+    case 11:
+      if (strncmp (mangled, "__InterfaceZ", len + 1) == 0)
+       {
+         /* The interface symbol for a given class.  */
+         string_prepend (decl, "Interface for ");
+         string_setlength (decl, string_length (decl) - 1);
+         mangled += len;
+         return mangled;
        }
+      break;
 
-      string_appendn (decl, mangled, len);
-      mangled += len;
+    case 12:
+      if (strncmp (mangled, "__ModuleInfoZ", len + 1) == 0)
+       {
+         /* The ModuleInfo symbol for a given module.  */
+         string_prepend (decl, "ModuleInfo for ");
+         string_setlength (decl, string_length (decl) - 1);
+         mangled += len;
+         return mangled;
+       }
+      break;
     }
 
+  string_appendn (decl, mangled, len);
+  mangled += len;
+
   return mangled;
 }
 
@@ -868,13 +1138,13 @@ dlang_parse_integer (string *decl, const char *mangled, char type)
   if (type == 'a' || type == 'u' || type == 'w')
     {
       /* Parse character value.  */
-      char value[10];
-      int pos = 10;
+      char value[20];
+      int pos = sizeof(value);
       int width = 0;
-      char *endptr;
-      long val = strtol (mangled, &endptr, 10);
+      unsigned long val;
 
-      if (endptr == NULL || val < 0)
+      mangled = dlang_number (mangled, &val);
+      if (mangled == NULL)
        return NULL;
 
       string_append (decl, "'");
@@ -920,22 +1190,20 @@ dlang_parse_integer (string *decl, const char *mangled, char type)
          for (; width > 0; width--)
            value[--pos] = '0';
 
-         string_appendn (decl, &(value[pos]), 10 - pos);
+         string_appendn (decl, &(value[pos]), sizeof(value) - pos);
        }
       string_append (decl, "'");
-      mangled = endptr;
     }
   else if (type == 'b')
     {
       /* Parse boolean value.  */
-      char *endptr;
-      long val = strtol (mangled, &endptr, 10);
+      unsigned long val;
 
-      if (endptr == NULL || val < 0)
+      mangled = dlang_number (mangled, &val);
+      if (mangled == NULL)
        return NULL;
 
       string_append (decl, val ? "true" : "false");
-      mangled = endptr;
     }
   else
     {
@@ -943,6 +1211,9 @@ dlang_parse_integer (string *decl, const char *mangled, char type)
       const char *numptr = mangled;
       size_t num = 0;
 
+      if (! ISDIGIT (*mangled))
+       return NULL;
+
       while (ISDIGIT (*mangled))
        {
          num++;
@@ -975,9 +1246,6 @@ dlang_parse_integer (string *decl, const char *mangled, char type)
 static const char *
 dlang_parse_real (string *decl, const char *mangled)
 {
-  char buffer[64];
-  int len = 0;
-
   /* Handle NAN and +-INF.  */
   if (strncmp (mangled, "NAN", 3) == 0)
     {
@@ -1001,23 +1269,22 @@ dlang_parse_real (string *decl, const char *mangled)
   /* Hexadecimal prefix and leading bit.  */
   if (*mangled == 'N')
     {
-      buffer[len++] = '-';
+      string_append (decl, "-");
       mangled++;
     }
 
   if (!ISXDIGIT (*mangled))
     return NULL;
 
-  buffer[len++] = '0';
-  buffer[len++] = 'x';
-  buffer[len++] = *mangled;
-  buffer[len++] = '.';
+  string_append (decl, "0x");
+  string_appendn (decl, mangled, 1);
+  string_append (decl, ".");
   mangled++;
 
   /* Significand.  */
   while (ISXDIGIT (*mangled))
     {
-      buffer[len++] = *mangled;
+      string_appendn (decl, mangled, 1);
       mangled++;
     }
 
@@ -1025,110 +1292,80 @@ dlang_parse_real (string *decl, const char *mangled)
   if (*mangled != 'P')
     return NULL;
 
-  buffer[len++] = 'p';
+  string_append (decl, "p");
   mangled++;
 
   if (*mangled == 'N')
     {
-      buffer[len++] = '-';
+      string_append (decl, "-");
       mangled++;
     }
 
   while (ISDIGIT (*mangled))
     {
-      buffer[len++] = *mangled;
+      string_appendn (decl, mangled, 1);
       mangled++;
     }
 
-  /* Write out the demangled hexadecimal, rather than trying to
-     convert the buffer into a floating-point value.  */
-  buffer[len] = '\0';
-  len = strlen (buffer);
-  string_appendn (decl, buffer, len);
   return mangled;
 }
 
-/* Convert VAL from an ascii hexdigit to value.  */
-static char
-ascii2hex (char val)
-{
-  if (val >= 'a' && val <= 'f')
-    return (val - 'a' + 10);
-
-  if (val >= 'A' && val <= 'F')
-    return (val - 'A' + 10);
-
-  if (val >= '0' && val <= '9')
-    return (val - '0');
-
-  return 0;
-}
-
 /* Extract the string value from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
 dlang_parse_string (string *decl, const char *mangled)
 {
   char type = *mangled;
-  char *endptr;
-  long len;
+  unsigned long len;
 
   mangled++;
-  len = strtol (mangled, &endptr, 10);
-
-  if (endptr == NULL || len < 0)
-    return NULL;
-
-  mangled = endptr;
-  if (*mangled != '_')
+  mangled = dlang_number (mangled, &len);
+  if (mangled == NULL || *mangled != '_')
     return NULL;
 
   mangled++;
   string_append (decl, "\"");
   while (len--)
     {
-      if (ISXDIGIT (mangled[0]) && ISXDIGIT (mangled[1]))
+      char val;
+      const char *endptr = dlang_hexdigit (mangled, &val);
+
+      if (endptr == NULL)
+       return NULL;
+
+      /* Sanitize white and non-printable characters.  */
+      switch (val)
        {
-         char a = ascii2hex (mangled[0]);
-         char b = ascii2hex (mangled[1]);
-         char val = (a << 4) | b;
+       case ' ':
+         string_append (decl, " ");
+         break;
+       case '\t':
+         string_append (decl, "\\t");
+         break;
+       case '\n':
+         string_append (decl, "\\n");
+         break;
+       case '\r':
+         string_append (decl, "\\r");
+         break;
+       case '\f':
+         string_append (decl, "\\f");
+         break;
+       case '\v':
+         string_append (decl, "\\v");
+         break;
 
-         /* Sanitize white and non-printable characters.  */
-         switch (val)
+       default:
+         if (ISPRINT (val))
+           string_appendn (decl, &val, 1);
+         else
            {
-           case ' ':
-             string_append (decl, " ");
-             break;
-           case '\t':
-             string_append (decl, "\\t");
-             break;
-           case '\n':
-             string_append (decl, "\\n");
-             break;
-           case '\r':
-             string_append (decl, "\\r");
-             break;
-           case '\f':
-             string_append (decl, "\\f");
-             break;
-           case '\v':
-             string_append (decl, "\\v");
-             break;
-
-           default:
-             if (ISPRINT (val))
-               string_appendn (decl, &val, 1);
-             else
-               {
-                 string_append (decl, "\\x");
-                 string_appendn (decl, mangled, 2);
-               }
+             string_append (decl, "\\x");
+             string_appendn (decl, mangled, 2);
            }
        }
-      else
-       return NULL;
 
-      mangled += 2;
+      mangled = endptr;
     }
   string_append (decl, "\"");
 
@@ -1143,17 +1380,19 @@ dlang_parse_string (string *decl, const char *mangled)
 static const char *
 dlang_parse_arrayliteral (string *decl, const char *mangled)
 {
-  char *endptr;
-  long elements = strtol (mangled, &endptr, 10);
+  unsigned long elements;
 
-  if (endptr == NULL || elements < 0)
+  mangled = dlang_number (mangled, &elements);
+  if (mangled == NULL)
     return NULL;
 
-  mangled = endptr;
   string_append (decl, "[");
   while (elements--)
     {
       mangled = dlang_value (decl, mangled, NULL, '\0');
+      if (mangled == NULL)
+       return NULL;
+
       if (elements != 0)
        string_append (decl, ", ");
     }
@@ -1167,19 +1406,23 @@ dlang_parse_arrayliteral (string *decl, const char *mangled)
 static const char *
 dlang_parse_assocarray (string *decl, const char *mangled)
 {
-  char *endptr;
-  long elements = strtol (mangled, &endptr, 10);
+  unsigned long elements;
 
-  if (endptr == NULL || elements < 0)
+  mangled = dlang_number (mangled, &elements);
+  if (mangled == NULL)
     return NULL;
 
-  mangled = endptr;
   string_append (decl, "[");
   while (elements--)
     {
       mangled = dlang_value (decl, mangled, NULL, '\0');
+      if (mangled == NULL)
+       return NULL;
+
       string_append (decl, ":");
       mangled = dlang_value (decl, mangled, NULL, '\0');
+      if (mangled == NULL)
+       return NULL;
 
       if (elements != 0)
        string_append (decl, ", ");
@@ -1194,13 +1437,12 @@ dlang_parse_assocarray (string *decl, const char *mangled)
 static const char *
 dlang_parse_structlit (string *decl, const char *mangled, const char *name)
 {
-  char *endptr;
-  long args = strtol (mangled, &endptr, 10);
+  unsigned long args;
 
-  if (endptr == NULL || args < 0)
+  mangled = dlang_number (mangled, &args);
+  if (mangled == NULL)
     return NULL;
 
-  mangled = endptr;
   if (name != NULL)
     string_append (decl, name);
 
@@ -1208,6 +1450,9 @@ dlang_parse_structlit (string *decl, const char *mangled, const char *name)
   while (args--)
     {
       mangled = dlang_value (decl, mangled, NULL, '\0');
+      if (mangled == NULL)
+       return NULL;
+
       if (args != 0)
        string_append (decl, ", ");
     }
@@ -1241,9 +1486,11 @@ dlang_value (string *decl, const char *mangled, const char *name, char type)
 
     case 'i':
       mangled++;
-      if (*mangled < '0' || *mangled > '9')
-       return NULL;
       /* Fall through */
+
+      /* There really should always be an `i' before encoded numbers, but there
+        wasn't in early versions of D2, so this case range must remain for
+        backwards compatibility.  */
     case '0': case '1': case '2': case '3': case '4':
     case '5': case '6': case '7': case '8': case '9':
       mangled = dlang_parse_integer (decl, mangled, type);
@@ -1296,143 +1543,118 @@ dlang_value (string *decl, const char *mangled, const char *name, char type)
   return mangled;
 }
 
-/* Extract the type modifiers from MANGLED and return the string
-   length that it consumes in MANGLED on success or 0 on failure.  */
-static int
-dlang_type_modifier_p (const char *mangled)
+/* Extract and demangle the symbol in MANGLED and append it to DECL.
+   Returns the remaining signature on success or NULL on failure.  */
+static const char *
+dlang_parse_mangle (string *decl, const char *mangled, struct dlang_info *info)
 {
-  int i;
-
-  switch (*mangled)
-    {
-    case 'x': case 'y':
-      return 1;
+  /* A D mangled symbol is comprised of both scope and type information.
+
+       MangleName:
+           _D QualifiedName Type
+           _D QualifiedName Z
+           ^
+     The caller should have guaranteed that the start pointer is at the
+     above location.
+     Note that type is never a function type, but only the return type of
+     a function or the type of a variable.
+   */
+  mangled += 2;
 
-    case 'O':
-      mangled++;
-      i = dlang_type_modifier_p (mangled);
-      return i + 1;
+  mangled = dlang_parse_qualified (decl, mangled, info, 1);
 
-    case 'N':
-      mangled++;
-      if (*mangled == 'g')
+  if (mangled != NULL)
+    {
+      /* Artificial symbols end with 'Z' and have no type.  */
+      if (*mangled == 'Z')
+       mangled++;
+      else
        {
-         mangled++;
-         i = dlang_type_modifier_p (mangled);
-         return i + 2;
-       }
-    }
-
-  return 0;
-}
+         /* Discard the declaration or return type.  */
+         string type;
 
-/* Extract the function calling convention from MANGLED and
-   return 1 on success or 0 on failure.  */
-static int
-dlang_call_convention_p (const char *mangled)
-{
-  /* Prefix for functions needing 'this' */
-  if (*mangled == 'M')
-    {
-      mangled++;
-      /* Also skip over any type modifiers.  */
-      mangled += dlang_type_modifier_p (mangled);
+         string_init (&type);
+         mangled = dlang_type (&type, mangled, info);
+         string_delete (&type);
+       }
     }
 
-  switch (*mangled)
-    {
-    case 'F': case 'U': case 'V':
-    case 'W': case 'R': case 'Y':
-      return 1;
-
-    default:
-      return 0;
-    }
+  return mangled;
 }
 
-/* Extract and demangle the symbol in MANGLED and append it to DECL.
+/* Extract and demangle the qualified symbol in MANGLED and append it to DECL.
+   SUFFIX_MODIFIERS is 1 if we are printing modifiers on this after the symbol.
    Returns the remaining signature on success or NULL on failure.  */
 static const char *
-dlang_parse_symbol (string *decl, const char *mangled,
-                   enum dlang_symbol_kinds kind)
+dlang_parse_qualified (string *decl, const char *mangled,
+                      struct dlang_info *info, int suffix_modifiers)
 {
-  int saved;
+  /* Qualified names are identifiers separated by their encoded length.
+     Nested functions also encode their argument types without specifying
+     what they return.
+
+       QualifiedName:
+           SymbolFunctionName
+           SymbolFunctionName QualifiedName
+           ^
+
+       SymbolFunctionName:
+           SymbolName
+           SymbolName TypeFunctionNoReturn
+           SymbolName M TypeFunctionNoReturn
+           SymbolName M TypeModifiers TypeFunctionNoReturn
+
+     The start pointer should be at the above location.
+   */
   size_t n = 0;
   do
     {
       if (n++)
        string_append (decl, ".");
 
-      mangled = dlang_identifier (decl, mangled, kind);
+      /* Skip over anonymous symbols.  */
+      while (*mangled == '0')
+       mangled++;
+
+      mangled = dlang_identifier (decl, mangled, info);
 
-      if (mangled && dlang_call_convention_p (mangled))
+      /* Consume the encoded arguments.  However if this is not followed by the
+        next encoded length or mangle type, then this is not a continuation of
+        a qualified name, in which case we backtrack and return the current
+        unconsumed position of the mangled decl.  */
+      if (mangled && (*mangled == 'M' || dlang_call_convention_p (mangled)))
        {
          string mods;
-         const char *start = NULL;
-         int checkpoint = 0;
+         const char *start = mangled;
+         int saved = string_length (decl);
 
-         /* Skip over 'this' parameter.  */
-         if (*mangled == 'M')
-           mangled++;
+         /* Save the type modifiers for appending at the end if needed.  */
+         string_init (&mods);
 
-         /* We have reached here because we expect an extern(Pascal) function.
-            However this is so rare, that it is more likely a template value
-            parameter.  Since this can't be assumed, first attempt parsing
-            the symbol as a function, and then back out on failure.  */
-         if (*mangled == 'V')
+         /* Skip over 'this' parameter and type modifiers.  */
+         if (*mangled == 'M')
            {
-             start = mangled;
-             checkpoint = string_length (decl);
+             mangled++;
+             mangled = dlang_type_modifiers (&mods, mangled);
+             string_setlength (decl, saved);
            }
 
-         /* Save the type modifiers for appending at the end.  */
-         string_init (&mods);
-         mangled = dlang_type_modifiers (&mods, mangled);
-
-         /* Skip over calling convention and attributes in qualified name.  */
-         saved = string_length (decl);
-         mangled = dlang_call_convention (decl, mangled);
-         mangled = dlang_attributes (decl, mangled);
-         string_setlength (decl, saved);
+         mangled = dlang_function_type_noreturn (decl, NULL, NULL,
+                                                 mangled, info);
+         if (suffix_modifiers)
+           string_appendn (decl, mods.b, string_length (&mods));
 
-         string_append (decl, "(");
-         mangled = dlang_function_args (decl, mangled);
-         string_append (decl, ")");
-
-         /* Add any const/immutable/shared modifier. */
-         string_appendn (decl, mods.b, string_length (&mods));
-         string_delete (&mods);
-
-         if (mangled == NULL && checkpoint != 0)
+         if (mangled == NULL || *mangled == '\0')
            {
+             /* Did not match the rule we were looking for.  */
              mangled = start;
-             string_setlength (decl, checkpoint);
+             string_setlength (decl, saved);
            }
-       }
-    }
-  while (mangled && ISDIGIT (*mangled));
-
-  /* Only top-level symbols or function template parameters have
-     a type that needs checking.  */
-  if (kind == dlang_top_level || kind == dlang_function)
-    {
-      /* Artificial symbols end with 'Z' and have no type.  */
-      if (mangled && *mangled == 'Z')
-       mangled++;
-      else
-       {
-         saved = string_length (decl);
-         mangled = dlang_type (decl, mangled);
-         string_setlength (decl, saved);
-       }
 
-      /* Check that the entire symbol was successfully demangled.  */
-      if (kind == dlang_top_level)
-       {
-         if (mangled == NULL || *mangled != '\0')
-           return NULL;
+         string_delete (&mods);
        }
     }
+  while (mangled && dlang_symbol_name_p (mangled, info));
 
   return mangled;
 }
@@ -1440,20 +1662,22 @@ dlang_parse_symbol (string *decl, const char *mangled,
 /* Demangle the tuple from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_parse_tuple (string *decl, const char *mangled)
+dlang_parse_tuple (string *decl, const char *mangled, struct dlang_info *info)
 {
-  char *endptr;
-  long elements = strtol (mangled, &endptr, 10);
+  unsigned long elements;
 
-  if (endptr == NULL || elements < 0)
+  mangled = dlang_number (mangled, &elements);
+  if (mangled == NULL)
     return NULL;
 
-  mangled = endptr;
   string_append (decl, "Tuple!(");
 
   while (elements--)
     {
-      mangled = dlang_type (decl, mangled);
+      mangled = dlang_type (decl, mangled, info);
+      if (mangled == NULL)
+       return NULL;
+
       if (elements != 0)
        string_append (decl, ", ");
     }
@@ -1462,10 +1686,71 @@ dlang_parse_tuple (string *decl, const char *mangled)
   return mangled;
 }
 
+/* Demangle the template symbol parameter from MANGLED and append it to DECL.
+   Return the remaining string on success or NULL on failure.  */
+static const char *
+dlang_template_symbol_param (string *decl, const char *mangled,
+                            struct dlang_info *info)
+{
+  if (strncmp (mangled, "_D", 2) == 0
+      && dlang_symbol_name_p (mangled + 2, info))
+    return dlang_parse_mangle (decl, mangled, info);
+
+  if (*mangled == 'Q')
+    return dlang_parse_qualified (decl, mangled, info, 0);
+
+  unsigned long len;
+  const char *endptr = dlang_number (mangled, &len);
+
+  if (endptr == NULL || len == 0)
+    return NULL;
+
+  /* In template parameter symbols generated by the frontend up to 2.076,
+     the symbol length is encoded and the first character of the mangled
+     name can be a digit.  This causes ambiguity issues because the digits
+     of the two numbers are adjacent.  */
+  long psize = len;
+  const char *pend;
+  int saved = string_length (decl);
+
+  /* Work backwards until a match is found.  */
+  for (pend = endptr; endptr != NULL; pend--)
+    {
+      mangled = pend;
+
+      /* Reached the beginning of the pointer to the name length,
+        try parsing the entire symbol.  */
+      if (psize == 0)
+       {
+         psize = len;
+         pend = endptr;
+         endptr = NULL;
+       }
+
+      /* Check whether template parameter is a function with a valid
+        return type or an untyped identifier.  */
+      if (dlang_symbol_name_p (mangled, info))
+       mangled = dlang_parse_qualified (decl, mangled, info, 0);
+      else if (strncmp (mangled, "_D", 2) == 0
+              && dlang_symbol_name_p (mangled + 2, info))
+       mangled = dlang_parse_mangle (decl, mangled, info);
+
+      /* Check for name length mismatch.  */
+      if (mangled && (endptr == NULL || (mangled - pend) == psize))
+       return mangled;
+
+      psize /= 10;
+      string_setlength (decl, saved);
+    }
+
+  /* No match on any combinations.  */
+  return NULL;
+}
+
 /* Demangle the argument list from MANGLED and append it to DECL.
    Return the remaining string on success or NULL on failure.  */
 static const char *
-dlang_template_args (string *decl, const char *mangled)
+dlang_template_args (string *decl, const char *mangled, struct dlang_info *info)
 {
   size_t n = 0;
 
@@ -1489,11 +1774,11 @@ dlang_template_args (string *decl, const char *mangled)
        {
        case 'S': /* Symbol parameter.  */
          mangled++;
-         mangled = dlang_parse_symbol (decl, mangled, dlang_template_param);
+         mangled = dlang_template_symbol_param (decl, mangled, info);
          break;
        case 'T': /* Type parameter.  */
          mangled++;
-         mangled = dlang_type (decl, mangled);
+         mangled = dlang_type (decl, mangled, info);
          break;
        case 'V': /* Value parameter.  */
        {
@@ -1504,10 +1789,20 @@ dlang_template_args (string *decl, const char *mangled)
          mangled++;
          type = *mangled;
 
+         if (type == 'Q')
+           {
+             /* Value type is a back reference, peek at the real type.  */
+             const char *backref;
+             if (dlang_backref (mangled, &backref, info) == NULL)
+               return NULL;
+
+             type = *backref;
+           }
+
          /* In the few instances where the type is actually desired in
             the output, it should precede the value from dlang_value.  */
          string_init (&name);
-         mangled = dlang_type (&name, mangled);
+         mangled = dlang_type (&name, mangled, info);
          string_need (&name, 1);
          *(name.p) = '\0';
 
@@ -1515,7 +1810,20 @@ dlang_template_args (string *decl, const char *mangled)
          string_delete (&name);
          break;
        }
+       case 'X': /* Externally mangled parameter.  */
+       {
+         unsigned long len;
+         const char *endptr;
+
+         mangled++;
+         endptr = dlang_number (mangled, &len);
+         if (endptr == NULL || strlen (endptr) < len)
+           return NULL;
 
+         string_appendn (decl, endptr, len);
+         mangled = endptr + len;
+         break;
+       }
        default:
          return NULL;
        }
@@ -1525,42 +1833,63 @@ dlang_template_args (string *decl, const char *mangled)
 }
 
 /* Extract and demangle the template symbol in MANGLED, expected to
-   be made up of LEN characters, and append it to DECL.
+   be made up of LEN characters (-1 if unknown), and append it to DECL.
    Returns the remaining signature on success or NULL on failure.  */
 static const char *
-dlang_parse_template (string *decl, const char *mangled, long len)
+dlang_parse_template (string *decl, const char *mangled,
+                     struct dlang_info *info, unsigned long len)
 {
   const char *start = mangled;
+  string args;
 
   /* Template instance names have the types and values of its parameters
      encoded into it.
 
        TemplateInstanceName:
            Number __T LName TemplateArgs Z
+           Number __U LName TemplateArgs Z
                   ^
      The start pointer should be at the above location, and LEN should be
      the value of the decoded number.
    */
-  if (strncmp (mangled, "__T", 3) != 0)
+
+  /* Template symbol.  */
+  if (!dlang_symbol_name_p (mangled + 3, info) || mangled[3] == '0')
     return NULL;
 
   mangled += 3;
 
   /* Template identifier.  */
-  mangled = dlang_identifier (decl, mangled, dlang_template_ident);
+  mangled = dlang_identifier (decl, mangled, info);
 
   /* Template arguments.  */
+  string_init (&args);
+  mangled = dlang_template_args (&args, mangled, info);
+
   string_append (decl, "!(");
-  mangled = dlang_template_args (decl, mangled);
+  string_appendn (decl, args.b, string_length (&args));
   string_append (decl, ")");
 
+  string_delete (&args);
+
   /* Check for template name length mismatch.  */
-  if (mangled && (mangled - start) != len)
+  if (len != TEMPLATE_LENGTH_UNKNOWN
+      && mangled
+      && (unsigned long) (mangled - start) != len)
     return NULL;
 
   return mangled;
 }
 
+/* Initialize the information structure we use to pass around information.  */
+static void
+dlang_demangle_init_info (const char *mangled, int last_backref,
+                         struct dlang_info *info)
+{
+  info->s = mangled;
+  info->last_backref = last_backref;
+}
+
 /* Extract and demangle the symbol in MANGLED.  Returns the demangled
    signature on success or NULL on failure.  */
 
@@ -1584,9 +1913,13 @@ dlang_demangle (const char *mangled, int option ATTRIBUTE_UNUSED)
     }
   else
     {
-      mangled += 2;
+      struct dlang_info info;
+
+      dlang_demangle_init_info (mangled, strlen (mangled), &info);
+      mangled = dlang_parse_mangle (&decl, mangled, &info);
 
-      if (dlang_parse_symbol (&decl, mangled, dlang_top_level) == NULL)
+      /* Check that the entire symbol was successfully demangled.  */
+      if (mangled == NULL || *mangled != '\0')
        string_delete (&decl);
     }