aboutsummaryrefslogtreecommitdiff
path: root/libiberty/d-demangle.c
blob: cd3bc96303ecfbc4b1c998f76dfff46ed37e5572 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
/* Demangler for the D programming language
   Copyright (C) 2014-2020 Free Software Foundation, Inc.
   Written by Iain Buclaw (ibuclaw@gdcproject.org)

This file is part of the libiberty library.
Libiberty is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

In addition to the permissions in the GNU Library General Public
License, the Free Software Foundation gives you unlimited permission
to link the compiled version of this file into combinations with other
programs, and to distribute those combinations without any restriction
coming from the use of this file.  (The Library Public License
restrictions do apply in other respects; for example, they cover
modification of the file, and distribution when not linked into a
combined executable.)

Libiberty 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
Library General Public License for more details.

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.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif

#include "safe-ctype.h"

#include <sys/types.h>
#include <string.h>
#include <stdio.h>

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#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 */
{				/*  '\0' terminated.  */
  char *b;			/* pointer to start of string */
  char *p;			/* pointer after last character */
  char *e;			/* pointer after end of allocated space */
} string;

static void
string_need (string *s, size_t n)
{
  size_t tem;

  if (s->b == NULL)
    {
      if (n < 32)
	{
	  n = 32;
	}
      s->p = s->b = XNEWVEC (char, n);
      s->e = s->b + n;
    }
  else if ((size_t) (s->e - s->p) < n)
    {
      tem = s->p - s->b;
      n += tem;
      n *= 2;
      s->b = XRESIZEVEC (char, s->b, n);
      s->p = s->b + tem;
      s->e = s->b + n;
    }
}

static void
string_delete (string *s)
{
  if (s->b != NULL)
    {
      XDELETEVEC (s->b);
      s->b = s->e = s->p = NULL;
    }
}

static void
string_init (string *s)
{
  s->b = s->p = s->e = NULL;
}

static int
string_length (string *s)
{
  if (s->p == s->b)
    {
      return 0;
    }
  return s->p - s->b;
}

static void
string_setlength (string *s, int n)
{
  if (n - string_length (s) < 0)
    {
      s->p = s->b + n;
    }
}

static void
string_append (string *p, const char *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, size_t n)
{
  if (n != 0)
    {
      string_need (p, n);
      memcpy (p->p, s, n);
      p->p += n;
    }
}

static void
string_prependn (string *p, const char *s, size_t n)
{
  char *q;

  if (n != 0)
    {
      string_need (p, n);
      for (q = p->p - 1; q >= p->b; q--)
	{
	  q[n] = q[0];
	}
      memcpy (p->b, s, n);
      p->p += n;
    }
}

static void
string_prepend (string *p, const char *s)
{
  if (s != NULL && *s != '\0')
    {
      string_prependn (p, s, strlen (s));
    }
}

/* Demangle information structure we pass around.  */
struct dlang_info
{
  /* 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_type (string *, const char *,
					struct dlang_info *);

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_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;

  if (ISDIGIT (*mangled))
    return 1;

  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.  */
static const char *
dlang_call_convention (string *decl, const char *mangled)
{
  if (mangled == NULL || *mangled == '\0')
    return NULL;

  switch (*mangled)
    {
    case 'F': /* (D) */
      mangled++;
      break;
    case 'U': /* (C) */
      mangled++;
      string_append (decl, "extern(C) ");
      break;
    case 'W': /* (Windows) */
      mangled++;
      string_append (decl, "extern(Windows) ");
      break;
    case 'V': /* (Pascal) */
      mangled++;
      string_append (decl, "extern(Pascal) ");
      break;
    case 'R': /* (C++) */
      mangled++;
      string_append (decl, "extern(C++) ");
      break;
    case 'Y': /* (Objective-C) */
      mangled++;
      string_append (decl, "extern(Objective-C) ");
      break;
    default:
      return NULL;
    }

  return mangled;
}

/* Extract the type modifiers from MANGLED and append them to DECL.
   Returns the remaining signature on success or NULL on failure.  */
static const char *
dlang_type_modifiers (string *decl, const char *mangled)
{
  if (mangled == NULL || *mangled == '\0')
    return NULL;

  switch (*mangled)
    {
    case 'x': /* const */
      mangled++;
      string_append (decl, " const");
      return mangled;
    case 'y': /* immutable */
      mangled++;
      string_append (decl, " immutable");
      return mangled;
    case 'O': /* shared */
      mangled++;
      string_append (decl, " shared");
      return dlang_type_modifiers (decl, mangled);
    case 'N':
      mangled++;
      if (*mangled == 'g') /* wild */
	{
	  mangled++;
	  string_append (decl, " inout");
	  return dlang_type_modifiers (decl, mangled);
	}
      else
	return NULL;

    default:
      return mangled;
    }
}

/* Demangle the D function attributes from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_attributes (string *decl, const char *mangled)
{
  if (mangled == NULL || *mangled == '\0')
    return NULL;

  while (*mangled == 'N')
    {
      mangled++;
      switch (*mangled)
	{
	case 'a': /* pure */
	  mangled++;
	  string_append (decl, "pure ");
	  continue;
	case 'b': /* nothrow */
	  mangled++;
	  string_append (decl, "nothrow ");
	  continue;
	case 'c': /* ref */
	  mangled++;
	  string_append (decl, "ref ");
	  continue;
	case 'd': /* @property */
	  mangled++;
	  string_append (decl, "@property ");
	  continue;
	case 'e': /* @trusted */
	  mangled++;
	  string_append (decl, "@trusted ");
	  continue;
	case 'f': /* @safe */
	  mangled++;
	  string_append (decl, "@safe ");
	  continue;
	case 'g':
	case 'h':
	case 'k':
	  /* inout parameter is represented as 'Ng'.
	     vector parameter is represented as 'Nh'.
	     return paramenter is represented as 'Nk'.
	     If we see this, then we know we're really in the
	     parameter list.  Rewind and break.  */
	  mangled--;
	  break;
	case 'i': /* @nogc */
	  mangled++;
	  string_append (decl, "@nogc ");
	  continue;
	case 'j': /* return */
	  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;
	}
      break;
    }

  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, struct dlang_info *info)
{
  string attr, args, type;

  if (mangled == NULL || *mangled == '\0')
    return NULL;

  /* The order of the mangled string is:
	CallConvention FuncAttrs Arguments ArgClose Type

     The demangled string is re-ordered as:
	CallConvention Type Arguments FuncAttrs
   */
  string_init (&attr);
  string_init (&args);
  string_init (&type);

  mangled = dlang_function_type_noreturn (&args, decl, &attr, mangled, info);

  /* Function return type.  */
  mangled = dlang_type (&type, mangled, info);

  /* Append to decl in order. */
  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);
  string_delete (&type);
  return 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, struct dlang_info *info)
{
  size_t n = 0;

  while (mangled && *mangled != '\0')
    {
      switch (*mangled)
	{
	case 'X': /* (variadic T t...) style.  */
	  mangled++;
	  string_append (decl, "...");
	  return mangled;
	case 'Y': /* (variadic T t, ...) style.  */
	  mangled++;
	  if (n != 0)
	    string_append (decl, ", ");
	  string_append (decl, "...");
	  return mangled;
	case 'Z': /* Normal function.  */
	  mangled++;
	  return mangled;
	}

      if (n++)
	string_append (decl, ", ");

      if (*mangled == 'M') /* scope(T) */
	{
	  mangled++;
	  string_append (decl, "scope ");
	}

      if (mangled[0] == 'N' && mangled[1] == 'k') /* return(T) */
	{
	  mangled += 2;
	  string_append (decl, "return ");
	}

      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 ");
	  break;
	case 'K': /* ref(T) */
	  mangled++;
	  string_append (decl, "ref ");
	  break;
	case 'L': /* lazy(T) */
	  mangled++;
	  string_append (decl, "lazy ");
	  break;
	}
      mangled = dlang_type (decl, mangled, info);
    }

  return 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, struct dlang_info *info)
{
  if (mangled == NULL || *mangled == '\0')
    return NULL;

  switch (*mangled)
    {
    case 'O': /* shared(T) */
      mangled++;
      string_append (decl, "shared(");
      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, info);
      string_append (decl, ")");
      return mangled;
    case 'y': /* immutable(T) */
      mangled++;
      string_append (decl, "immutable(");
      mangled = dlang_type (decl, mangled, info);
      string_append (decl, ")");
      return mangled;
    case 'N':
      mangled++;
      if (*mangled == 'g') /* wild(T) */
	{
	  mangled++;
	  string_append (decl, "inout(");
	  mangled = dlang_type (decl, mangled, info);
	  string_append (decl, ")");
	  return mangled;
	}
      else if (*mangled == 'h') /* vector(T) */
	{
	  mangled++;
	  string_append (decl, "__vector(");
	  mangled = dlang_type (decl, mangled, info);
	  string_append (decl, ")");
	  return mangled;
	}
      else
	return NULL;
    case 'A': /* dynamic array (T[]) */
      mangled++;
      mangled = dlang_type (decl, mangled, info);
      string_append (decl, "[]");
      return mangled;
    case 'G': /* static array (T[N]) */
    {
      const char *numptr;
      size_t num = 0;
      mangled++;

      numptr = mangled;
      while (ISDIGIT (*mangled))
	{
	  num++;
	  mangled++;
	}
      mangled = dlang_type (decl, mangled, info);
      string_append (decl, "[");
      string_appendn (decl, numptr, num);
      string_append (decl, "]");
      return mangled;
    }
    case 'H': /* associative array (T[T]) */
    {
      string type;
      size_t sztype;
      mangled++;

      string_init (&type);
      mangled = dlang_type (&type, mangled, info);
      sztype = string_length (&type);

      mangled = dlang_type (decl, mangled, info);
      string_append (decl, "[");
      string_appendn (decl, type.b, sztype);
      string_append (decl, "]");

      string_delete (&type);
      return mangled;
    }
    case 'P': /* pointer (T*) */
      mangled++;
      if (!dlang_call_convention_p (mangled))
	{
	  mangled = dlang_type (decl, mangled, info);
	  string_append (decl, "*");
	  return mangled;
	}
      /* 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 'C': /* class T */
    case 'S': /* struct T */
    case 'E': /* enum T */
    case 'T': /* typedef T */
      mangled++;
      return dlang_parse_qualified (decl, mangled, info, 0);
    case 'D': /* delegate T */
    {
      string mods;
      size_t szmods;
      mangled++;

      string_init (&mods);
      mangled = dlang_type_modifiers (&mods, mangled);
      szmods = string_length (&mods);

      /* 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);

      string_delete (&mods);
      return mangled;
    }
    case 'B': /* tuple T */
      mangled++;
      return dlang_parse_tuple (decl, mangled, info);

    /* Basic types */
    case 'n':
      mangled++;
      string_append (decl, "none");
      return mangled;
    case 'v':
      mangled++;
      string_append (decl, "void");
      return mangled;
    case 'g':
      mangled++;
      string_append (decl, "byte");
      return mangled;
    case 'h':
      mangled++;
      string_append (decl, "ubyte");
      return mangled;
    case 's':
      mangled++;
      string_append (decl, "short");
      return mangled;
    case 't':
      mangled++;
      string_append (decl, "ushort");
      return mangled;
    case 'i':
      mangled++;
      string_append (decl, "int");
      return mangled;
    case 'k':
      mangled++;
      string_append (decl, "uint");
      return mangled;
    case 'l':
      mangled++;
      string_append (decl, "long");
      return mangled;
    case 'm':
      mangled++;
      string_append (decl, "ulong");
      return mangled;
    case 'f':
      mangled++;
      string_append (decl, "float");
      return mangled;
    case 'd':
      mangled++;
      string_append (decl, "double");
      return mangled;
    case 'e':
      mangled++;
      string_append (decl, "real");
      return mangled;

    /* Imaginary and Complex types */
    case 'o':
      mangled++;
      string_append (decl, "ifloat");
      return mangled;
    case 'p':
      mangled++;
      string_append (decl, "idouble");
      return mangled;
    case 'j':
      mangled++;
      string_append (decl, "ireal");
      return mangled;
    case 'q':
      mangled++;
      string_append (decl, "cfloat");
      return mangled;
    case 'r':
      mangled++;
      string_append (decl, "cdouble");
      return mangled;
    case 'c':
      mangled++;
      string_append (decl, "creal");
      return mangled;

    /* Other types */
    case 'b':
      mangled++;
      string_append (decl, "bool");
      return mangled;
    case 'a':
      mangled++;
      string_append (decl, "char");
      return mangled;
    case 'u':
      mangled++;
      string_append (decl, "wchar");
      return mangled;
    case 'w':
      mangled++;
      string_append (decl, "dchar");
      return mangled;
    case 'z':
      mangled++;
      switch (*mangled)
	{
	case 'i':
	  mangled++;
	  string_append (decl, "cent");
	  return mangled;
	case 'k':
	  mangled++;
	  string_append (decl, "ucent");
	  return mangled;
	}
      return NULL;

    /* Back referenced type.  */
    case 'Q':
      return dlang_type_backref (decl, mangled, info, 0);

    default: /* unhandled */
      return NULL;
    }
}

/* 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, struct dlang_info *info)
{
  unsigned long len;

  if (mangled == NULL || *mangled == '\0')
    return NULL;

  if (*mangled == 'Q')
    return dlang_symbol_backref (decl, mangled, info);

  /* 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);

  const char *endptr = dlang_number (mangled, &len);

  if (endptr == NULL || len == 0)
    return NULL;

  if (strlen (endptr) < len)
    return NULL;

  mangled = endptr;

  /* 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);

  return dlang_lname (decl, mangled, len);
}

/* 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)
    {
    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_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 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 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 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 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;
}

/* Extract the integer value from MANGLED and append it to DECL,
   where TYPE is the type it should be represented as.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_parse_integer (string *decl, const char *mangled, char type)
{
  if (type == 'a' || type == 'u' || type == 'w')
    {
      /* Parse character value.  */
      char value[20];
      int pos = sizeof(value);
      int width = 0;
      unsigned long val;

      mangled = dlang_number (mangled, &val);
      if (mangled == NULL)
	return NULL;

      string_append (decl, "'");

      if (type == 'a' && val >= 0x20 && val < 0x7F)
	{
	  /* Represent as a character literal.  */
	  char c = (char) val;
	  string_appendn (decl, &c, 1);
	}
      else
	{
	  /* Represent as a hexadecimal value.  */
	  switch (type)
	    {
	    case 'a': /* char */
	      string_append (decl, "\\x");
	      width = 2;
	      break;
	    case 'u': /* wchar */
	      string_append (decl, "\\u");
	      width = 4;
	      break;
	    case 'w': /* dchar */
	      string_append (decl, "\\U");
	      width = 8;
	      break;
	    }

	  while (val > 0)
	    {
	      int digit = val % 16;

	      if (digit < 10)
		value[--pos] = (char)(digit + '0');
	      else
		value[--pos] = (char)((digit - 10) + 'a');

	      val /= 16;
	      width--;
	    }

	  for (; width > 0; width--)
	    value[--pos] = '0';

	  string_appendn (decl, &(value[pos]), sizeof(value) - pos);
	}
      string_append (decl, "'");
    }
  else if (type == 'b')
    {
      /* Parse boolean value.  */
      unsigned long val;

      mangled = dlang_number (mangled, &val);
      if (mangled == NULL)
	return NULL;

      string_append (decl, val ? "true" : "false");
    }
  else
    {
      /* Parse integer value.  */
      const char *numptr = mangled;
      size_t num = 0;

      if (! ISDIGIT (*mangled))
	return NULL;

      while (ISDIGIT (*mangled))
	{
	  num++;
	  mangled++;
	}
      string_appendn (decl, numptr, num);

      /* Append suffix.  */
      switch (type)
	{
	case 'h': /* ubyte */
	case 't': /* ushort */
	case 'k': /* uint */
	  string_append (decl, "u");
	  break;
	case 'l': /* long */
	  string_append (decl, "L");
	  break;
	case 'm': /* ulong */
	  string_append (decl, "uL");
	  break;
	}
    }

  return mangled;
}

/* Extract the floating-point value from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_parse_real (string *decl, const char *mangled)
{
  /* Handle NAN and +-INF.  */
  if (strncmp (mangled, "NAN", 3) == 0)
    {
      string_append (decl, "NaN");
      mangled += 3;
      return mangled;
    }
  else if (strncmp (mangled, "INF", 3) == 0)
    {
      string_append (decl, "Inf");
      mangled += 3;
      return mangled;
    }
  else if (strncmp (mangled, "NINF", 4) == 0)
    {
      string_append (decl, "-Inf");
      mangled += 4;
      return mangled;
    }

  /* Hexadecimal prefix and leading bit.  */
  if (*mangled == 'N')
    {
      string_append (decl, "-");
      mangled++;
    }

  if (!ISXDIGIT (*mangled))
    return NULL;

  string_append (decl, "0x");
  string_appendn (decl, mangled, 1);
  string_append (decl, ".");
  mangled++;

  /* Significand.  */
  while (ISXDIGIT (*mangled))
    {
      string_appendn (decl, mangled, 1);
      mangled++;
    }

  /* Exponent.  */
  if (*mangled != 'P')
    return NULL;

  string_append (decl, "p");
  mangled++;

  if (*mangled == 'N')
    {
      string_append (decl, "-");
      mangled++;
    }

  while (ISDIGIT (*mangled))
    {
      string_appendn (decl, mangled, 1);
      mangled++;
    }

  return mangled;
}

/* 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;
  unsigned long len;

  mangled++;
  mangled = dlang_number (mangled, &len);
  if (mangled == NULL || *mangled != '_')
    return NULL;

  mangled++;
  string_append (decl, "\"");
  while (len--)
    {
      char val;
      const char *endptr = dlang_hexdigit (mangled, &val);

      if (endptr == NULL)
	return NULL;

      /* Sanitize white and non-printable characters.  */
      switch (val)
	{
	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);
	    }
	}

      mangled = endptr;
    }
  string_append (decl, "\"");

  if (type != 'a')
    string_appendn (decl, &type, 1);

  return mangled;
}

/* Extract the static array value from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_parse_arrayliteral (string *decl, const char *mangled)
{
  unsigned long elements;

  mangled = dlang_number (mangled, &elements);
  if (mangled == NULL)
    return NULL;

  string_append (decl, "[");
  while (elements--)
    {
      mangled = dlang_value (decl, mangled, NULL, '\0');
      if (mangled == NULL)
	return NULL;

      if (elements != 0)
	string_append (decl, ", ");
    }

  string_append (decl, "]");
  return mangled;
}

/* Extract the associative array value from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_parse_assocarray (string *decl, const char *mangled)
{
  unsigned long elements;

  mangled = dlang_number (mangled, &elements);
  if (mangled == NULL)
    return NULL;

  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, ", ");
    }

  string_append (decl, "]");
  return mangled;
}

/* Extract the struct literal value for NAME from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_parse_structlit (string *decl, const char *mangled, const char *name)
{
  unsigned long args;

  mangled = dlang_number (mangled, &args);
  if (mangled == NULL)
    return NULL;

  if (name != NULL)
    string_append (decl, name);

  string_append (decl, "(");
  while (args--)
    {
      mangled = dlang_value (decl, mangled, NULL, '\0');
      if (mangled == NULL)
	return NULL;

      if (args != 0)
	string_append (decl, ", ");
    }

  string_append (decl, ")");
  return mangled;
}

/* Extract the value from MANGLED and append it to DECL.
   Return the remaining string on success or NULL on failure.  */
static const char *
dlang_value (string *decl, const char *mangled, const char *name, char type)
{
  if (mangled == NULL || *mangled == '\0')
    return NULL;

  switch (*mangled)
    {
      /* Null value.  */
    case 'n':
      mangled++;
      string_append (decl, "null");
      break;

      /* Integral values.  */
    case 'N':
      mangled++;
      string_append (decl, "-");
      mangled = dlang_parse_integer (decl, mangled, type);
      break;

    case 'i':
      mangled++;
      /* 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);
      break;

      /* Real value.  */
    case 'e':
      mangled++;
      mangled = dlang_parse_real (decl, mangled);
      break;

      /* Complex value.  */
    case 'c':
      mangled++;
      mangled = dlang_parse_real (decl, mangled);
      string_append (decl, "+");
      if (mangled == NULL || *mangled != 'c')
	return NULL;
      mangled++;
      mangled = dlang_parse_real (decl, mangled);
      string_append (decl, "i");
      break;

      /* String values.  */
    case 'a': /* UTF8 */
    case 'w': /* UTF16 */
    case 'd': /* UTF32 */
      mangled = dlang_parse_string (decl, mangled);
      break;

      /* Array values.  */
    case 'A':
      mangled++;
      if (type == 'H')
	mangled = dlang_parse_assocarray (decl, mangled);
      else
	mangled = dlang_parse_arrayliteral (decl, mangled);
      break;

      /* Struct values.  */
    case 'S':
      mangled++;
      mangled = dlang_parse_structlit (decl, mangled, name);
      break;

    default:
      return NULL;
    }

  return 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)
{
  /* 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;

  mangled = dlang_parse_qualified (decl, mangled, info, 1);

  if (mangled != NULL)
    {
      /* Artificial symbols end with 'Z' and have no type.  */
      if (*mangled == 'Z')
	mangled++;
      else
	{
	  /* Discard the declaration or return type.  */
	  string type;

	  string_init (&type);
	  mangled = dlang_type (&type, mangled, info);
	  string_delete (&type);
	}
    }

  return mangled;
}

/* 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_qualified (string *decl, const char *mangled,
		       struct dlang_info *info, int suffix_modifiers)
{
  /* 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, ".");

      /* Skip over anonymous symbols.  */
      while (*mangled == '0')
	mangled++;

      mangled = dlang_identifier (decl, mangled, info);

      /* 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 = mangled;
	  int saved = string_length (decl);

	  /* Save the type modifiers for appending at the end if needed.  */
	  string_init (&mods);

	  /* Skip over 'this' parameter and type modifiers.  */
	  if (*mangled == 'M')
	    {
	      mangled++;
	      mangled = dlang_type_modifiers (&mods, 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));

	  if (mangled == NULL || *mangled == '\0')
	    {
	      /* Did not match the rule we were looking for.  */
	      mangled = start;
	      string_setlength (decl, saved);
	    }

	  string_delete (&mods);
	}
    }
  while (mangled && dlang_symbol_name_p (mangled, info));

  return 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, struct dlang_info *info)
{
  unsigned long elements;

  mangled = dlang_number (mangled, &elements);
  if (mangled == NULL)
    return NULL;

  string_append (decl, "Tuple!(");

  while (elements--)
    {
      mangled = dlang_type (decl, mangled, info);
      if (mangled == NULL)
	return NULL;

      if (elements != 0)
	string_append (decl, ", ");
    }

  string_append (decl, ")");
  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, struct dlang_info *info)
{
  size_t n = 0;

  while (mangled && *mangled != '\0')
    {
      switch (*mangled)
	{
	case 'Z': /* End of parameter list.  */
	  mangled++;
	  return mangled;
	}

      if (n++)
	string_append (decl, ", ");

      /* Skip over specialised template prefix.  */
      if (*mangled == 'H')
	mangled++;

      switch (*mangled)
	{
	case 'S': /* Symbol parameter.  */
	  mangled++;
	  mangled = dlang_template_symbol_param (decl, mangled, info);
	  break;
	case 'T': /* Type parameter.  */
	  mangled++;
	  mangled = dlang_type (decl, mangled, info);
	  break;
	case 'V': /* Value parameter.  */
	{
	  string name;
	  char type;

	  /* Peek at the type.  */
	  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, info);
	  string_need (&name, 1);
	  *(name.p) = '\0';

	  mangled = dlang_value (decl, mangled, name.b, type);
	  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;
	}
    }

  return mangled;
}

/* Extract and demangle the template symbol in MANGLED, expected to
   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,
		      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.
   */

  /* Template symbol.  */
  if (!dlang_symbol_name_p (mangled + 3, info) || mangled[3] == '0')
    return NULL;

  mangled += 3;

  /* Template identifier.  */
  mangled = dlang_identifier (decl, mangled, info);

  /* Template arguments.  */
  string_init (&args);
  mangled = dlang_template_args (&args, mangled, info);

  string_append (decl, "!(");
  string_appendn (decl, args.b, string_length (&args));
  string_append (decl, ")");

  string_delete (&args);

  /* Check for template name length mismatch.  */
  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.  */

char *
dlang_demangle (const char *mangled, int option ATTRIBUTE_UNUSED)
{
  string decl;
  char *demangled = NULL;

  if (mangled == NULL || *mangled == '\0')
    return NULL;

  if (strncmp (mangled, "_D", 2) != 0)
    return NULL;

  string_init (&decl);

  if (strcmp (mangled, "_Dmain") == 0)
    {
      string_append (&decl, "D main");
    }
  else
    {
      struct dlang_info info;

      dlang_demangle_init_info (mangled, strlen (mangled), &info);
      mangled = dlang_parse_mangle (&decl, mangled, &info);

      /* Check that the entire symbol was successfully demangled.  */
      if (mangled == NULL || *mangled != '\0')
	string_delete (&decl);
    }

  if (string_length (&decl) > 0)
    {
      string_need (&decl, 1);
      *(decl.p) = '\0';
      demangled = decl.b;
    }

  return demangled;
}