summaryrefslogtreecommitdiff
path: root/Source/Swig/typemap.c
blob: 607ab6d1099cd6013295884b95ba3aef2fa0483c (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
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
/* -----------------------------------------------------------------------------
 * This file is part of SWIG, which is licensed as a whole under version 3 
 * (or any later version) of the GNU General Public License. Some additional
 * terms also apply to certain portions of SWIG. The full details of the SWIG
 * license and copyrights can be found in the LICENSE and COPYRIGHT files
 * included with the SWIG source code as distributed by the SWIG developers
 * and at http://www.swig.org/legal.html.
 *
 * typemap.c
 *
 * A somewhat generalized implementation of SWIG1.1 typemaps.
 * ----------------------------------------------------------------------------- */

char cvsroot_typemap_c[] = "$Id$";

#include "swig.h"
#include "cparse.h"
#include <ctype.h>

#if 0
#define SWIG_DEBUG
#endif

static int typemap_search_debug = 0;
static int typemaps_used_debug = 0;
static int in_typemap_search_multi = 0;

static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper *f, Node *file_line_node);

/* -----------------------------------------------------------------------------
 * Typemaps are stored in a collection of nested hash tables.  Something like
 * this:
 *
 * [ type ]
 *    +-------- [ name ]
 *    +-------- [ name ]
 *    
 * Each hash table [ type ] or [ name ] then contains references to the
 * different typemap methods.    These are referenced by names such as
 * "tmap:in", "tmap:out", "tmap:argout", and so forth.
 *
 * The object corresponding to a specific typemap method has the following attributes:
 *
 *    "type"    -  Typemap type
 *    "pname"   -  Parameter name
 *    "code"    -  Typemap code
 *    "source"  -  Source directive (%apply or %typemap) for the typemap
 *    "locals"  -  Local variables (if any)
 *    "kwargs"  -  Typemap attributes
 * 
 * Example for a typemap method named "in":
 *   %typemap(in, warning="987:my warning", noblock=1) int &my_int (int tmp) "$1 = $input;"
 *
 *    "type"    -  r.int
 *    "pname"   -  my_int
 *    "code"    -  $1 = $input;
 *    "source"  -  typemap(in) int &my_int
 *    "locals"  -  int tmp
 *    "kwargs"  -  warning="987:my typemap warning", foo=123
 * 
 * ----------------------------------------------------------------------------- */

#define MAX_SCOPE  32


static Hash *typemaps[MAX_SCOPE];
static int tm_scope = 0;

static Hash *get_typemap(int tm_scope, const SwigType *type) {
  Hash *tm = 0;
  SwigType *dtype = 0;
  SwigType *hashtype;

  if (SwigType_istemplate(type)) {
    String *ty = Swig_symbol_template_deftype(type, 0);
    dtype = Swig_symbol_type_qualify(ty, 0);
    type = dtype;
    Delete(ty);
  }

  /* remove unary scope operator (::) prefix indicating global scope for looking up in the hashmap */
  hashtype = SwigType_remove_global_scope_prefix(type);
  tm = Getattr(typemaps[tm_scope], hashtype);

  Delete(dtype);
  Delete(hashtype);

  return tm;
}

static void set_typemap(int tm_scope, const SwigType *type, Hash *tm) {
  SwigType *hashtype = 0;
  if (SwigType_istemplate(type)) {
    String *ty = Swig_symbol_template_deftype(type, 0);
    String *tyq = Swig_symbol_type_qualify(ty, 0);
    hashtype = SwigType_remove_global_scope_prefix(tyq);
    Delete(tyq);
    Delete(ty);
  } else {
    hashtype = SwigType_remove_global_scope_prefix(type);
  }

  /* note that the unary scope operator (::) prefix indicating global scope has been removed from the type */
  Setattr(typemaps[tm_scope], hashtype, tm);

  Delete(hashtype);
}


/* -----------------------------------------------------------------------------
 * Swig_typemap_init()
 *
 * Initialize the typemap system
 * ----------------------------------------------------------------------------- */

void Swig_typemap_init() {
  int i;
  for (i = 0; i < MAX_SCOPE; i++) {
    typemaps[i] = 0;
  }
  typemaps[0] = NewHash();
  tm_scope = 0;
}

static String *typemap_method_name(const_String_or_char_ptr tmap_method) {
  static Hash *names = 0;
  String *s;
  /* Due to "interesting" object-identity semantics of DOH,
     we have to make sure that we only intern strings without object
     identity into the hash table.

     (typemap_attach_kwargs calls typemap_method_name several times with
     the "same" String *tmap_method (i.e., same object identity) but differing
     string values.)

     Most other callers work around this by using char* rather than
     String *.
     -- mkoeppe, Jun 17, 2003
   */
  const char *method_without_object_identity = Char(tmap_method);
  if (!names)
    names = NewHash();
  s = Getattr(names, method_without_object_identity);
  if (s)
    return s;
  s = NewStringf("tmap:%s", tmap_method);
  Setattr(names, method_without_object_identity, s);
  Delete(s);
  return s;
}

#if 0
/* -----------------------------------------------------------------------------
 * Swig_typemap_new_scope()
 * 
 * Create a new typemap scope
 * ----------------------------------------------------------------------------- */

void Swig_typemap_new_scope() {
  tm_scope++;
  typemaps[tm_scope] = NewHash();
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_pop_scope()
 *
 * Pop the last typemap scope off
 * ----------------------------------------------------------------------------- */

Hash *Swig_typemap_pop_scope() {
  if (tm_scope > 0) {
    return typemaps[tm_scope--];
  }
  return 0;
}
#endif

/* ----------------------------------------------------------------------------- 
 * typemap_register()
 *
 * Internal implementation for Swig_typemap_register()
 * ----------------------------------------------------------------------------- */

static void typemap_register(const_String_or_char_ptr tmap_method, ParmList *parms, const_String_or_char_ptr code, ParmList *locals, ParmList *kwargs, String *source_directive) {
  Hash *tm;
  Hash *tm1;
  Hash *tm2;
  Parm *np;
  String *tm_method;
  SwigType *type;
  String *pname;

  if (!parms)
    return;
  tm_method = typemap_method_name(tmap_method);

  /* Register the first type in the parameter list */

  type = Getattr(parms, "type");
  pname = Getattr(parms, "name");

  /* See if this type has been seen before */
  tm = get_typemap(tm_scope, type);
  if (!tm) {
    tm = NewHash();
    set_typemap(tm_scope, type, tm);
    Delete(tm);
  }
  if (pname) {
    /* See if parameter has been seen before */
    tm1 = Getattr(tm, pname);
    if (!tm1) {
      tm1 = NewHash();
      Setattr(tm, pname, tm1);
      Delete(tm1);
    }
    tm = tm1;
  }

  /* Now see if this typemap method has been seen before */
  tm2 = Getattr(tm, tm_method);
  if (!tm2) {
    tm2 = NewHash();
    Setattr(tm, tm_method, tm2);
    Delete(tm2);
  }

  /* For a multi-argument typemap, the typemap code and information
     is really only stored in the last argument.  However, to
     make this work, we perform a really neat trick using
     the typemap method name.

     For example, consider this typemap

     %typemap(in) (int foo, int *bar, char *blah[]) {
     ...
     }

     To store it, we look at typemaps for the following:

     typemap method            type-name
     ----------------------------------------------
     "in"                      int foo
     "in-int+foo:"             int *bar
     "in-int+foo:-p.int+bar:   char *blah[]

     Notice how the typemap method name expands to encode information about
     previous arguments.        

   */

  np = nextSibling(parms);
  if (np) {
    /* Make an entirely new typemap method key */
    String *multi_tmap_method = NewStringf("%s-%s+%s:", tmap_method, type, pname);

    /* Now reregister on the remaining arguments */
    typemap_register(multi_tmap_method, np, code, locals, kwargs, source_directive);

    Delete(multi_tmap_method);
  } else {
    ParmList *clocals = CopyParmList(locals);
    ParmList *ckwargs = CopyParmList(kwargs);

    Setfile(tm2, Getfile(code));
    Setline(tm2, Getline(code));
    Setattr(tm2, "code", code);
    Setattr(tm2, "type", type);
    Setattr(tm2, "source", source_directive);
    if (pname) {
      Setattr(tm2, "pname", pname);
    }
    Setattr(tm2, "locals", clocals);
    Setattr(tm2, "kwargs", ckwargs);

    Delete(clocals);
    Delete(ckwargs);
  }
}

/* ----------------------------------------------------------------------------- 
 * Swig_typemap_register()
 *
 * Add a new, possibly multi-argument, typemap
 * ----------------------------------------------------------------------------- */

void Swig_typemap_register(const_String_or_char_ptr tmap_method, ParmList *parms, const_String_or_char_ptr code, ParmList *locals, ParmList *kwargs) {
  String *parms_str = ParmList_str_multibrackets(parms);
  String *source_directive = NewStringf("typemap(%s) %s", tmap_method, parms_str);

  typemap_register(tmap_method, parms, code, locals, kwargs, source_directive);

  Delete(source_directive);
  Delete(parms_str);
}

/* -----------------------------------------------------------------------------
 * typemap_get()
 *
 * Retrieve typemap information from current scope.
 * ----------------------------------------------------------------------------- */

static Hash *typemap_get(SwigType *type, const_String_or_char_ptr name, int scope) {
  Hash *tm, *tm1;
  /* See if this type has been seen before */
  if ((scope < 0) || (scope > tm_scope))
    return 0;
  tm = get_typemap(scope, type);
  if (!tm) {
    return 0;
  }
  if ((name) && Len(name)) {
    tm1 = Getattr(tm, name);
    return tm1;
  }
  return tm;
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_copy()
 *
 * Copy a typemap
 * ----------------------------------------------------------------------------- */

int Swig_typemap_copy(const_String_or_char_ptr tmap_method, ParmList *srcparms, ParmList *parms) {
  Hash *tm = 0;
  String *tm_method;
  Parm *p;
  String *pname;
  SwigType *ptype;
  int ts = tm_scope;
  String *tm_methods, *multi_tmap_method;
  if (ParmList_len(parms) != ParmList_len(srcparms))
    return -1;

  tm_method = typemap_method_name(tmap_method);
  while (ts >= 0) {
    p = srcparms;
    tm_methods = NewString(tm_method);
    while (p) {
      ptype = Getattr(p, "type");
      pname = Getattr(p, "name");

      /* Lookup the type */
      tm = typemap_get(ptype, pname, ts);
      if (!tm)
	break;

      tm = Getattr(tm, tm_methods);
      if (!tm)
	break;

      /* Got a match.  Look for next typemap */
      multi_tmap_method = NewStringf("%s-%s+%s:", tm_methods, ptype, pname);
      Delete(tm_methods);
      tm_methods = multi_tmap_method;
      p = nextSibling(p);
    }
    Delete(tm_methods);

    if (!p && tm) {
      /* Got some kind of match */
      String *parms_str = ParmList_str_multibrackets(parms);
      String *srcparms_str = ParmList_str_multibrackets(srcparms);
      String *source_directive = NewStringf("typemap(%s) %s = %s", tmap_method, parms_str, srcparms_str);

      typemap_register(tmap_method, parms, Getattr(tm, "code"), Getattr(tm, "locals"), Getattr(tm, "kwargs"), source_directive);

      Delete(source_directive);
      Delete(srcparms_str);
      Delete(parms_str);
      return 0;
    }
    ts--;
  }
  /* Not found */
  return -1;

}

/* -----------------------------------------------------------------------------
 * Swig_typemap_clear()
 *
 * Delete a multi-argument typemap
 * ----------------------------------------------------------------------------- */

void Swig_typemap_clear(const_String_or_char_ptr tmap_method, ParmList *parms) {
  SwigType *type;
  String *name;
  Parm *p;
  String *multi_tmap_method;
  Hash *tm = 0;

  /* This might not work */
  multi_tmap_method = NewString(tmap_method);
  p = parms;
  while (p) {
    type = Getattr(p, "type");
    name = Getattr(p, "name");
    tm = typemap_get(type, name, tm_scope);
    if (!tm)
      return;
    p = nextSibling(p);
    if (p)
      Printf(multi_tmap_method, "-%s+%s:", type, name);
  }
  if (tm) {
    tm = Getattr(tm, typemap_method_name(multi_tmap_method));
    if (tm) {
      Delattr(tm, "code");
      Delattr(tm, "locals");
      Delattr(tm, "kwargs");
    }
  }
  Delete(multi_tmap_method);
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_apply()
 *
 * Multi-argument %apply directive.  This is pretty horrible so I sure hope
 * it works.
 * ----------------------------------------------------------------------------- */

static int count_args(String *s) {
  /* Count up number of arguments */
  int na = 0;
  char *c = Char(s);
  while (*c) {
    if (*c == '+')
      na++;
    c++;
  }
  return na;
}

int Swig_typemap_apply(ParmList *src, ParmList *dest) {
  String *ssig, *dsig;
  Parm *p, *np, *lastp, *dp, *lastdp = 0;
  int narg = 0;
  int ts = tm_scope;
  SwigType *type = 0, *name;
  Hash *tm, *sm;
  int match = 0;

  /*  Printf(stdout,"apply : %s --> %s\n", ParmList_str(src), ParmList_str(dest)); */

  /* Create type signature of source */
  ssig = NewStringEmpty();
  dsig = NewStringEmpty();
  p = src;
  dp = dest;
  lastp = 0;
  while (p) {
    lastp = p;
    lastdp = dp;
    np = nextSibling(p);
    if (np) {
      Printf(ssig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name"));
      Printf(dsig, "-%s+%s:", Getattr(dp, "type"), Getattr(dp, "name"));
      narg++;
    }
    p = np;
    dp = nextSibling(dp);
  }

  /* make sure a typemap node exists for the last destination node */
  type = Getattr(lastdp, "type");
  tm = get_typemap(tm_scope, type);
  if (!tm) {
    tm = NewHash();
    set_typemap(tm_scope, type, tm);
    Delete(tm);
  }
  name = Getattr(lastdp, "name");
  if (name) {
    Hash *tm1 = Getattr(tm, name);
    if (!tm1) {
      tm1 = NewHash();
      Setattr(tm, NewString(name), tm1);
      Delete(tm1);
    }
    tm = tm1;
  }

  /* This is a little nasty.  We need to go searching for all possible typemaps in the
     source and apply them to the target */

  type = Getattr(lastp, "type");
  name = Getattr(lastp, "name");

  while (ts >= 0) {

    /* See if there is a matching typemap in this scope */
    sm = typemap_get(type, name, ts);

    /* if there is not matching, look for a typemap in the
       original typedef, if any, like in:

       typedef unsigned long size_t;
       ...
       %apply(size_t) {my_size};  ==>  %apply(unsigned long) {my_size};
     */
    if (!sm) {
      SwigType *ntype = SwigType_typedef_resolve(type);
      if (ntype && (Cmp(ntype, type) != 0)) {
	sm = typemap_get(ntype, name, ts);
      }
      Delete(ntype);
    }

    if (sm) {
      /* Got a typemap.  Need to only merge attributes for methods that match our signature */
      Iterator ki;
      match = 1;
      for (ki = First(sm); ki.key; ki = Next(ki)) {
	/* Check for a signature match with the source signature */
	if ((count_args(ki.key) == narg) && (Strstr(ki.key, ssig))) {
	  String *oldm;
	  /* A typemap we have to copy */
	  String *nkey = Copy(ki.key);
	  Replace(nkey, ssig, dsig, DOH_REPLACE_ANY);

	  /* Make sure the typemap doesn't already exist in the target map */

	  oldm = Getattr(tm, nkey);
	  if (!oldm || (!Getattr(tm, "code"))) {
	    String *code;
	    ParmList *locals;
	    ParmList *kwargs;
	    Hash *sm1 = ki.item;

	    code = Getattr(sm1, "code");
	    locals = Getattr(sm1, "locals");
	    kwargs = Getattr(sm1, "kwargs");
	    if (code) {
	      String *src_str = ParmList_str_multibrackets(src);
	      String *dest_str = ParmList_str_multibrackets(dest);
	      String *source_directive = NewStringf("apply %s { %s }", src_str, dest_str);

	      Replace(nkey, dsig, "", DOH_REPLACE_ANY);
	      Replace(nkey, "tmap:", "", DOH_REPLACE_ANY);
	      typemap_register(nkey, dest, code, locals, kwargs, source_directive);

	      Delete(source_directive);
	      Delete(dest_str);
	      Delete(src_str);
	    }
	  }
	  Delete(nkey);
	}
      }
    }
    ts--;
  }
  Delete(ssig);
  Delete(dsig);
  return match;
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_clear_apply()
 *
 * %clear directive.   Clears all typemaps for a type (in the current scope only).    
 * ----------------------------------------------------------------------------- */

/* Multi-argument %clear directive */
void Swig_typemap_clear_apply(Parm *parms) {
  String *tsig;
  Parm *p, *np, *lastp;
  int narg = 0;
  Hash *tm;
  String *name;

  /* Create a type signature of the parameters */
  tsig = NewStringEmpty();
  p = parms;
  lastp = 0;
  while (p) {
    lastp = p;
    np = nextSibling(p);
    if (np) {
      Printf(tsig, "-%s+%s:", Getattr(p, "type"), Getattr(p, "name"));
      narg++;
    }
    p = np;
  }
  tm = get_typemap(tm_scope, Getattr(lastp, "type"));
  if (!tm) {
    Delete(tsig);
    return;
  }
  name = Getattr(lastp, "name");
  if (name) {
    tm = Getattr(tm, name);
  }
  if (tm) {
    /* Clear typemaps that match our signature */
    Iterator ki, ki2;
    char *ctsig = Char(tsig);
    for (ki = First(tm); ki.key; ki = Next(ki)) {
      char *ckey = Char(ki.key);
      if (strncmp(ckey, "tmap:", 5) == 0) {
	int na = count_args(ki.key);
	if ((na == narg) && strstr(ckey, ctsig)) {
	  Hash *h = ki.item;
	  for (ki2 = First(h); ki2.key; ki2 = Next(ki2)) {
	    Delattr(h, ki2.key);
	  }
	}
      }
    }
  }
  Delete(tsig);
}

/* Internal function to strip array dimensions. */
static SwigType *strip_arrays(SwigType *type) {
  SwigType *t;
  int ndim;
  int i;
  t = Copy(type);
  ndim = SwigType_array_ndim(t);
  for (i = 0; i < ndim; i++) {
    SwigType_array_setdim(t, i, "ANY");
  }
  return t;
}

static void debug_search_result_display(Node *tm) {
  if (tm)
    Printf(stdout, "  Using: %%%s\n", Getattr(tm, "source"));
  else
    Printf(stdout, "  None found\n");
}

/* -----------------------------------------------------------------------------
 * typemap_search_helper()
 *
 * Helper function for typemap_search to see if there is a type match in the typemap
 * tm. A match is sought in this order:
 * %typemap(tm_method) ctype cqualifiedname
 * %typemap(tm_method) ctype cname
 * %typemap(tm_method) ctype 
 * ----------------------------------------------------------------------------- */

static Hash *typemap_search_helper(int debug_display, Hash *tm, const String *tm_method, SwigType *ctype, const String *cqualifiedname, const String *cname, Hash **backup) {
  Hash *result = 0;
  Hash *tm1;
  if (debug_display && cqualifiedname)
    Printf(stdout, "  Looking for: %s\n", SwigType_str(ctype, cqualifiedname));
  if (tm && cqualifiedname) {
    tm1 = Getattr(tm, cqualifiedname);
    if (tm1) {
      result = Getattr(tm1, tm_method);	/* See if there is a type - qualified name match */
      if (result && Getattr(result, "code"))
	goto ret_result;
      if (result)
	*backup = result;
    }
  }
  if (debug_display && cname)
    Printf(stdout, "  Looking for: %s\n", SwigType_str(ctype, cname));
  if (tm && cname) {
    tm1 = Getattr(tm, cname);
    if (tm1) {
      result = Getattr(tm1, tm_method);	/* See if there is a type - name match */
      if (result && Getattr(result, "code"))
	goto ret_result;
      if (result)
	*backup = result;
    }
  }
  if (debug_display)
    Printf(stdout, "  Looking for: %s\n", SwigType_str(ctype, 0));
  if (tm) {
    result = Getattr(tm, tm_method);	/* See if there is simply a type without name match */
    if (result && Getattr(result, "code"))
      goto ret_result;
    if (result)
      *backup = result;
  }
ret_result:
  return result;
}

/* -----------------------------------------------------------------------------
 * typemap_search()
 *
 * Search for a typemap match. This is where the typemap pattern matching rules 
 * are implemented... tries to find the most specific typemap that includes a 
 * 'code' attribute.
 * ----------------------------------------------------------------------------- */

static Hash *typemap_search(const_String_or_char_ptr tmap_method, SwigType *type, const_String_or_char_ptr name, const_String_or_char_ptr qualifiedname, SwigType **matchtype, Node *node) {
  Hash *result = 0;
  Hash *tm;
  Hash *backup = 0;
  SwigType *primitive = 0;
  SwigType *ctype = 0;
  SwigType *ctype_unstripped = 0;
  int ts;
  int isarray;
  const String *cname = 0;
  const String *cqualifiedname = 0;
  String *tm_method = typemap_method_name(tmap_method);
  int debug_display = (in_typemap_search_multi == 0) && typemap_search_debug;

  if ((name) && Len(name))
    cname = name;
  if ((qualifiedname) && Len(qualifiedname))
    cqualifiedname = qualifiedname;
  ts = tm_scope;

  if (debug_display) {
    String *typestr = SwigType_str(type, cqualifiedname ? cqualifiedname : cname);
    Swig_diagnostic(Getfile(node), Getline(node), "Searching for a suitable '%s' typemap for: %s\n", tmap_method, typestr);
    Delete(typestr);
  }
  while (ts >= 0) {
    ctype = Copy(type);
    ctype_unstripped = Copy(ctype);
    while (ctype) {
      /* Try to get an exact type-match */
      tm = get_typemap(ts, ctype);
      result = typemap_search_helper(debug_display, tm, tm_method, ctype, cqualifiedname, cname, &backup);
      if (result && Getattr(result, "code"))
	goto ret_result;

      {
	/* Look for the type reduced to just the template prefix */
	SwigType *template_prefix = SwigType_istemplate_templateprefix(ctype);
	if (template_prefix) {
	  tm = get_typemap(ts, template_prefix);
	  result = typemap_search_helper(debug_display, tm, tm_method, template_prefix, cqualifiedname, cname, &backup);
	  Delete(template_prefix);
	  if (result && Getattr(result, "code"))
	    goto ret_result;
	}
      }

      /* look for [ANY] arrays */
      isarray = SwigType_isarray(ctype);
      if (isarray) {
	/* If working with arrays, strip away all of the dimensions and replace with "ANY".
	   See if that generates a match */
	SwigType *noarrays = strip_arrays(ctype);
	tm = get_typemap(ts, noarrays);
	result = typemap_search_helper(debug_display, tm, tm_method, noarrays, cqualifiedname, cname, &backup);
	Delete(noarrays);
	if (result && Getattr(result, "code"))
	  goto ret_result;
      }

      /* No match so far - try with a qualifier stripped (strip one qualifier at a time until none remain)
       * The order of stripping in SwigType_strip_single_qualifier is used to provide some sort of consistency
       * with the default (SWIGTYPE) typemap matching rules for the first qualifier to be stripped. */
      {
	SwigType *oldctype = ctype;
	ctype = SwigType_strip_single_qualifier(oldctype);
	if (!Equal(ctype, oldctype)) {
	  Delete(oldctype);
	  continue;
	}
	Delete(oldctype);
      }

      /* Once all qualifiers are stripped try resolve a typedef */
      {
	SwigType *oldctype = ctype;
	ctype = SwigType_typedef_resolve(ctype_unstripped);
	Delete(oldctype);
	ctype_unstripped = Copy(ctype);
      }
    }

    /* Hmmm. Well, no match seems to be found at all. See if there is some kind of default (SWIGTYPE) mapping */

    primitive = SwigType_default_create(type);
    while (primitive) {
      tm = get_typemap(ts, primitive);
      result = typemap_search_helper(debug_display, tm, tm_method, primitive, cqualifiedname, cname, &backup);
      if (result && Getattr(result, "code"))
	goto ret_result;

      {
	SwigType *nprim = SwigType_default_deduce(primitive);
	Delete(primitive);
	primitive = nprim;
      }
    }
    if (ctype != type) {
      Delete(ctype);
      ctype = 0;
    }
    ts--;			/* Hmmm. Nothing found in this scope.  Guess we'll go try another scope */
  }
  result = backup;

ret_result:
  Delete(primitive);
  if (matchtype)
    *matchtype = Copy(ctype);
  Delete(ctype);
  Delete(ctype_unstripped);
  return result;
}


/* -----------------------------------------------------------------------------
 * typemap_search_multi()
 *
 * Search for a multi-argument typemap.
 * ----------------------------------------------------------------------------- */

static Hash *typemap_search_multi(const_String_or_char_ptr tmap_method, ParmList *parms, int *nmatch) {
  SwigType *type;
  SwigType *mtype = 0;
  String *name;
  String *multi_tmap_method;
  Hash *tm;
  Hash *tm1 = 0;

  if (!parms) {
    *nmatch = 0;
    return 0;
  }
  type = Getattr(parms, "type");
  name = Getattr(parms, "name");

  /* Try to find a match on the first type */
  tm = typemap_search(tmap_method, type, name, 0, &mtype, parms);
  if (tm) {
    if (mtype && SwigType_isarray(mtype)) {
      Setattr(parms, "tmap:match", mtype);
    }
    Delete(mtype);
    multi_tmap_method = NewStringf("%s-%s+%s:", tmap_method, type, name);
    in_typemap_search_multi++;
    tm1 = typemap_search_multi(multi_tmap_method, nextSibling(parms), nmatch);
    in_typemap_search_multi--;
    if (tm1)
      tm = tm1;
    if (Getattr(tm, "code")) {
      *(nmatch) = *nmatch + 1;
      if (typemap_search_debug && tm1 && (in_typemap_search_multi == 0)) {
	Printf(stdout, "  Multi-argument typemap found...\n");
      }
    } else {
      tm = 0;
    }
    Delete(multi_tmap_method);
  }

  if (typemap_search_debug && (in_typemap_search_multi == 0))
    debug_search_result_display(tm);
  if (typemaps_used_debug && (in_typemap_search_multi == 0) && tm) {
    String *typestr = SwigType_str(type, name);
    Swig_diagnostic(Getfile(parms), Getline(parms), "Typemap for %s (%s) : %%%s\n", typestr, tmap_method, Getattr(tm, "source"));
    assert(Getfile(parms) && Len(Getfile(parms)) > 0); /* Missing file and line numbering information */
    Delete(typestr);
  }

  return tm;
}


/* -----------------------------------------------------------------------------
 * typemap_replace_vars()
 *
 * Replaces typemap variables on a string.  index is the $n variable.
 * type and pname are the type and parameter name.
 * ----------------------------------------------------------------------------- */

static void replace_local_types(ParmList *p, const String *name, const String *rep) {
  SwigType *t;
  while (p) {
    t = Getattr(p, "type");
    Replace(t, name, rep, DOH_REPLACE_ANY);
    p = nextSibling(p);
  }
}

static int check_locals(ParmList *p, const char *s) {
  while (p) {
    char *c = GetChar(p, "type");
    if (strstr(c, s))
      return 1;
    p = nextSibling(p);
  }
  return 0;
}

static int typemap_replace_vars(String *s, ParmList *locals, SwigType *type, SwigType *rtype, String *pname, String *lname, int index) {
  char var[512];
  char *varname;
  SwigType *ftype;
  int bare_substitution_count = 0;

  Replaceall(s, "$typemap", "$TYPEMAP"); /* workaround for $type substitution below */

  ftype = SwigType_typedef_resolve_all(type);

  if (!pname)
    pname = lname;
  {
    Parm *p;
    int rep = 0;
    p = locals;
    while (p) {
      if (Strchr(Getattr(p, "type"), '$'))
	rep = 1;
      p = nextSibling(p);
    }
    if (!rep)
      locals = 0;
  }

  sprintf(var, "$%d_", index);
  varname = &var[strlen(var)];

  /* If the original datatype was an array. We're going to go through and substitute
     its array dimensions */

  if (SwigType_isarray(type) || SwigType_isarray(ftype)) {
    String *size;
    int ndim;
    int i;
    if (SwigType_array_ndim(type) != SwigType_array_ndim(ftype))
      type = ftype;
    ndim = SwigType_array_ndim(type);
    size = NewStringEmpty();
    for (i = 0; i < ndim; i++) {
      String *dim = SwigType_array_getdim(type, i);
      if (index == 1) {
	char t[32];
	sprintf(t, "$dim%d", i);
	Replace(s, t, dim, DOH_REPLACE_ANY);
	replace_local_types(locals, t, dim);
      }
      sprintf(varname, "dim%d", i);
      Replace(s, var, dim, DOH_REPLACE_ANY);
      replace_local_types(locals, var, dim);
      if (Len(size))
	Putc('*', size);
      Append(size, dim);
      Delete(dim);
    }
    sprintf(varname, "size");
    Replace(s, var, size, DOH_REPLACE_ANY);
    replace_local_types(locals, var, size);
    Delete(size);
  }

  /* Parameter name substitution */
  if (index == 1) {
    Replace(s, "$parmname", pname, DOH_REPLACE_ANY);
  }
  strcpy(varname, "name");
  Replace(s, var, pname, DOH_REPLACE_ANY);

  /* Type-related stuff */
  {
    SwigType *star_type, *amp_type, *base_type, *lex_type;
    SwigType *ltype, *star_ltype, *amp_ltype;
    String *mangle, *star_mangle, *amp_mangle, *base_mangle, *base_name;
    String *descriptor, *star_descriptor, *amp_descriptor;
    String *ts;
    char *sc;

    sc = Char(s);

    if (strstr(sc, "type") || check_locals(locals, "type")) {
      /* Given type : $type */
      ts = SwigType_str(type, 0);
      if (index == 1) {
	Replace(s, "$type", ts, DOH_REPLACE_ANY);
	replace_local_types(locals, "$type", type);
      }
      strcpy(varname, "type");
      Replace(s, var, ts, DOH_REPLACE_ANY);
      replace_local_types(locals, var, type);
      Delete(ts);
      sc = Char(s);
    }
    if (strstr(sc, "ltype") || check_locals(locals, "ltype")) {
      /* Local type:  $ltype */
      ltype = SwigType_ltype(type);
      ts = SwigType_str(ltype, 0);
      if (index == 1) {
	Replace(s, "$ltype", ts, DOH_REPLACE_ANY);
	replace_local_types(locals, "$ltype", ltype);
      }
      strcpy(varname, "ltype");
      Replace(s, var, ts, DOH_REPLACE_ANY);
      replace_local_types(locals, var, ltype);
      Delete(ts);
      Delete(ltype);
      sc = Char(s);
    }
    if (strstr(sc, "mangle") || strstr(sc, "descriptor")) {
      /* Mangled type */

      mangle = SwigType_manglestr(type);
      if (index == 1)
	Replace(s, "$mangle", mangle, DOH_REPLACE_ANY);
      strcpy(varname, "mangle");
      Replace(s, var, mangle, DOH_REPLACE_ANY);

      descriptor = NewStringf("SWIGTYPE%s", mangle);

      if (index == 1)
	if (Replace(s, "$descriptor", descriptor, DOH_REPLACE_ANY))
	  SwigType_remember(type);

      strcpy(varname, "descriptor");
      if (Replace(s, var, descriptor, DOH_REPLACE_ANY))
	SwigType_remember(type);

      Delete(descriptor);
      Delete(mangle);
    }

    /* One pointer level removed */
    /* This creates variables of the form
       $*n_type
       $*n_ltype
     */

    if (SwigType_ispointer(ftype) || (SwigType_isarray(ftype)) || (SwigType_isreference(ftype))) {
      if (!(SwigType_isarray(type) || SwigType_ispointer(type) || SwigType_isreference(type))) {
	star_type = Copy(ftype);
      } else {
	star_type = Copy(type);
      }
      if (!SwigType_isreference(star_type)) {
	if (SwigType_isarray(star_type)) {
	  SwigType_del_element(star_type);
	} else {
	  SwigType_del_pointer(star_type);
	}
	ts = SwigType_str(star_type, 0);
	if (index == 1) {
	  Replace(s, "$*type", ts, DOH_REPLACE_ANY);
	  replace_local_types(locals, "$*type", star_type);
	}
	sprintf(varname, "$*%d_type", index);
	Replace(s, varname, ts, DOH_REPLACE_ANY);
	replace_local_types(locals, varname, star_type);
	Delete(ts);
      } else {
	SwigType_del_element(star_type);
      }
      star_ltype = SwigType_ltype(star_type);
      ts = SwigType_str(star_ltype, 0);
      if (index == 1) {
	Replace(s, "$*ltype", ts, DOH_REPLACE_ANY);
	replace_local_types(locals, "$*ltype", star_ltype);
      }
      sprintf(varname, "$*%d_ltype", index);
      Replace(s, varname, ts, DOH_REPLACE_ANY);
      replace_local_types(locals, varname, star_ltype);
      Delete(ts);
      Delete(star_ltype);

      star_mangle = SwigType_manglestr(star_type);
      if (index == 1)
	Replace(s, "$*mangle", star_mangle, DOH_REPLACE_ANY);

      sprintf(varname, "$*%d_mangle", index);
      Replace(s, varname, star_mangle, DOH_REPLACE_ANY);

      star_descriptor = NewStringf("SWIGTYPE%s", star_mangle);
      if (index == 1)
	if (Replace(s, "$*descriptor", star_descriptor, DOH_REPLACE_ANY))
	  SwigType_remember(star_type);
      sprintf(varname, "$*%d_descriptor", index);
      if (Replace(s, varname, star_descriptor, DOH_REPLACE_ANY))
	SwigType_remember(star_type);

      Delete(star_descriptor);
      Delete(star_mangle);
      Delete(star_type);
    } else {
      /* TODO: Signal error if one of the $* substitutions is
         requested */
    }
    /* One pointer level added */
    amp_type = Copy(type);
    SwigType_add_pointer(amp_type);
    ts = SwigType_str(amp_type, 0);
    if (index == 1) {
      Replace(s, "$&type", ts, DOH_REPLACE_ANY);
      replace_local_types(locals, "$&type", amp_type);
    }
    sprintf(varname, "$&%d_type", index);
    Replace(s, varname, ts, DOH_REPLACE_ANY);
    replace_local_types(locals, varname, amp_type);
    Delete(ts);

    amp_ltype = SwigType_ltype(type);
    SwigType_add_pointer(amp_ltype);
    ts = SwigType_str(amp_ltype, 0);

    if (index == 1) {
      Replace(s, "$&ltype", ts, DOH_REPLACE_ANY);
      replace_local_types(locals, "$&ltype", amp_ltype);
    }
    sprintf(varname, "$&%d_ltype", index);
    Replace(s, varname, ts, DOH_REPLACE_ANY);
    replace_local_types(locals, varname, amp_ltype);
    Delete(ts);
    Delete(amp_ltype);

    amp_mangle = SwigType_manglestr(amp_type);
    if (index == 1)
      Replace(s, "$&mangle", amp_mangle, DOH_REPLACE_ANY);
    sprintf(varname, "$&%d_mangle", index);
    Replace(s, varname, amp_mangle, DOH_REPLACE_ANY);

    amp_descriptor = NewStringf("SWIGTYPE%s", amp_mangle);
    if (index == 1)
      if (Replace(s, "$&descriptor", amp_descriptor, DOH_REPLACE_ANY))
	SwigType_remember(amp_type);
    sprintf(varname, "$&%d_descriptor", index);
    if (Replace(s, varname, amp_descriptor, DOH_REPLACE_ANY))
      SwigType_remember(amp_type);

    Delete(amp_descriptor);
    Delete(amp_mangle);
    Delete(amp_type);

    /* Base type */
    if (SwigType_isarray(type)) {
      SwigType *bt = Copy(type);
      Delete(SwigType_pop_arrays(bt));
      base_type = SwigType_str(bt, 0);
      Delete(bt);
    } else {
      base_type = SwigType_base(type);
    }

    base_name = SwigType_namestr(base_type);
    if (index == 1) {
      Replace(s, "$basetype", base_name, DOH_REPLACE_ANY);
      replace_local_types(locals, "$basetype", base_name);
    }
    strcpy(varname, "basetype");
    Replace(s, var, base_type, DOH_REPLACE_ANY);
    replace_local_types(locals, var, base_name);

    base_mangle = SwigType_manglestr(base_type);
    if (index == 1)
      Replace(s, "$basemangle", base_mangle, DOH_REPLACE_ANY);
    strcpy(varname, "basemangle");
    Replace(s, var, base_mangle, DOH_REPLACE_ANY);
    Delete(base_mangle);
    Delete(base_type);
    Delete(base_name);

    lex_type = SwigType_base(rtype);
    if (index == 1)
      Replace(s, "$lextype", lex_type, DOH_REPLACE_ANY);
    strcpy(varname, "lextype");
    Replace(s, var, lex_type, DOH_REPLACE_ANY);
    Delete(lex_type);
  }

  /* Replace any $n. with (&n)-> */
  {
    char temp[64];
    sprintf(var, "$%d.", index);
    sprintf(temp, "(&$%d)->", index);
    Replace(s, var, temp, DOH_REPLACE_ANY);
  }

  /* Replace the bare $n variable */
  sprintf(var, "$%d", index);
  bare_substitution_count = Replace(s, var, lname, DOH_REPLACE_ANY);
  Delete(ftype);
  return bare_substitution_count;
}

/* ------------------------------------------------------------------------
 * static typemap_locals()
 *
 * Takes a string, a parameter list and a wrapper function argument and
 * creates the local variables.
 * ------------------------------------------------------------------------ */

static void typemap_locals(DOHString * s, ParmList *l, Wrapper *f, int argnum) {
  Parm *p;
  char *new_name;

  p = l;
  while (p) {
    SwigType *pt = Getattr(p, "type");
    SwigType *at = SwigType_alttype(pt, 1);
    String *pn = Getattr(p, "name");
    String *value = Getattr(p, "value");
    if (at)
      pt = at;
    if (pn) {
      if (Len(pn) > 0) {
	String *str;
	int isglobal = 0;

	str = NewStringEmpty();

	if (strncmp(Char(pn), "_global_", 8) == 0) {
	  isglobal = 1;
	}

	/* If the user gave us $type as the name of the local variable, we'll use
	   the passed datatype instead */

	if ((argnum >= 0) && (!isglobal)) {
	  Printf(str, "%s%d", pn, argnum);
	} else {
	  Append(str, pn);
	}
	if (isglobal && Wrapper_check_local(f, str)) {
	  p = nextSibling(p);
	  Delete(str);
	  if (at)
	    Delete(at);
	  continue;
	}
	if (value) {
	  String *pstr = SwigType_str(pt, str);
	  new_name = Wrapper_new_localv(f, str, pstr, "=", value, NIL);
	  Delete(pstr);
	} else {
	  String *pstr = SwigType_str(pt, str);
	  new_name = Wrapper_new_localv(f, str, pstr, NIL);
	  Delete(pstr);
	}
	if (!isglobal) {
	  /* Substitute  */
	  Replace(s, pn, new_name, DOH_REPLACE_ID | DOH_REPLACE_NOQUOTE);
	}
	Delete(str);
      }
    }
    p = nextSibling(p);
    if (at)
      Delete(at);
  }
}

/* -----------------------------------------------------------------------------
 * typemap_warn()
 *
 * If any warning message is attached to this parameter's "tmap:<method>:warning"
 * attribute, print that warning message.
 * ----------------------------------------------------------------------------- */

static void typemap_warn(const_String_or_char_ptr tmap_method, Parm *p) {
  String *temp = NewStringf("%s:warning", tmap_method);
  String *w = Getattr(p, typemap_method_name(temp));
  Delete(temp);
  if (w) {
    Swig_warning(0, Getfile(p), Getline(p), "%s\n", w);
  }
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_lookup()
 *
 * Attach one or more typemaps to a node and optionally generate the typemap contents
 * into the wrapper.
 *
 * Looks for a typemap matching the given type and name and attaches the typemap code
 * and any typemap attributes to the provided node.
 *
 * The node should contain the "type" and "name" attributes for the typemap match on.
 * input. The typemap code and typemap attribute values are attached onto the node
 * prefixed with "tmap:". For example with tmap_method="in", the typemap code can be retrieved 
 * with a call to Getattr(node, "tmap:in") (this is also the string returned) and the 
 * "noblock" attribute can be retrieved with a call to Getattr(node, "tmap:in:noblock").
 *
 * tmap_method - typemap method, eg "in", "out", "newfree"
 * node        - the node to attach the typemap and typemap attributes to
 * lname       - name of variable to substitute $1, $2 etc for
 * f           - wrapper code to generate into if non null
 * actioncode  - code to generate into f before the out typemap code, unless
 *              the optimal attribute is set in the out typemap in which case
 *              $1 in the out typemap will be replaced  by the code in actioncode.
 * ----------------------------------------------------------------------------- */

static String *Swig_typemap_lookup_impl(const_String_or_char_ptr tmap_method, Node *node, const_String_or_char_ptr lname, Wrapper *f, String *actioncode) {
  SwigType *type;
  SwigType *mtype = 0;
  String *pname;
  String *qpname = 0;
  Hash *tm = 0;
  String *s = 0;
  String *sdef = 0;
  ParmList *locals;
  ParmList *kw;
  char temp[256];
  String *symname;
  String *cname = 0;
  String *clname = 0;
  char *cmethod = Char(tmap_method);
  int optimal_attribute = 0;
  int optimal_substitution = 0;
  int num_substitutions = 0;

  /* special case, we need to check for 'ref' call and set the default code 'sdef' */
  if (node && Cmp(tmap_method, "newfree") == 0) {
    sdef = Swig_ref_call(node, lname);
  }

  type = Getattr(node, "type");
  if (!type)
    return sdef;

  pname = Getattr(node, "name");

  if (pname && node && checkAttribute(node, "kind", "function")) {
    /* 
       For functions, add on a qualified name search, for example
       struct Foo {
         int *foo(int bar)   ->  Foo::foo
       };
     */
    Symtab *st = Getattr(node, "sym:symtab");
    String *qsn = st ? Swig_symbol_string_qualify(pname, st) : 0;
    if (qsn && Len(qsn) && !Equal(qsn, pname))
      qpname = qsn;
  }

  tm = typemap_search(tmap_method, type, pname, qpname, &mtype, node);
  if (typemap_search_debug)
    debug_search_result_display(tm);
  if (typemaps_used_debug && tm) {
    String *typestr = SwigType_str(type, qpname ? qpname : pname);
    Swig_diagnostic(Getfile(node), Getline(node), "Typemap for %s (%s) : %%%s\n", typestr, tmap_method, Getattr(tm, "source"));
    assert(Getfile(node) && Len(Getfile(node)) > 0); /* Missing file and line numbering information */
    Delete(typestr);
  }


  Delete(qpname);
  qpname = 0;

  if (!tm)
    return sdef;

  s = Getattr(tm, "code");
  if (!s)
    return sdef;

  /* Empty typemap. No match */
  if (Cmp(s, "pass") == 0)
    return sdef;

  s = Copy(s);			/* Make a local copy of the typemap code */

  /* Attach kwargs - ie the typemap attributes */
  kw = Getattr(tm, "kwargs");
  while (kw) {
    String *value = Copy(Getattr(kw, "value"));
    String *kwtype = Getattr(kw, "type");
    char *ckwname = Char(Getattr(kw, "name"));
    if (kwtype) {
      String *mangle = Swig_string_mangle(kwtype);
      Append(value, mangle);
      Delete(mangle);
    }
    sprintf(temp, "%s:%s", cmethod, ckwname);
    Setattr(node, typemap_method_name(temp), value);
    if (Cmp(temp, "out:optimal") == 0)
      optimal_attribute = (Cmp(value, "0") != 0) ? 1 : 0;
    Delete(value);
    kw = nextSibling(kw);
  }
  
  if (optimal_attribute) {
    /* Note: "out" typemap is the only typemap that will have the "optimal" attribute set.
     * If f and actioncode are NULL, then the caller is just looking to attach the "out" attributes
     * ie, not use the typemap code, otherwise both f and actioncode must be non null. */
    if (actioncode) {
      clname = Copy(actioncode);
      /* check that the code in the typemap can be used in this optimal way.
       * The code should be in the form "result = ...;\n". We need to extract
       * the "..." part. This may not be possible for various reasons, eg
       * code added by %exception. This optimal code generation is bit of a
       * hack and circumvents the normal requirement for a temporary variable 
       * to hold the result returned from a wrapped function call.
       */
      if (Strncmp(clname, "result = ", 9) == 0) {
        int numreplacements = Replace(clname, "result = ", "", DOH_REPLACE_ID_BEGIN);
        if (numreplacements == 1) {
          numreplacements = Replace(clname, ";\n", "", DOH_REPLACE_ID_END);
          if (numreplacements == 1) {
            if (Strchr(clname, ';') == 0) {
              lname = clname;
              actioncode = 0;
              optimal_substitution = 1;
            }
          }
        }
      }
      if (!optimal_substitution) {
        Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(node), Getline(node), "Method %s usage of the optimal attribute ignored\n", Swig_name_decl(node));
        Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_IGNORED, Getfile(s), Getline(s), "in the out typemap as the following cannot be used to generate optimal code: %s\n", clname);
        Delattr(node, "tmap:out:optimal");
      }
    } else {
      assert(!f);
    }
  }
  if (actioncode) {
    assert(f);
    Append(f->code, actioncode);
  }

  /* emit local variables declared in typemap, eg emit declarations for aa and bb in:
   * %typemap(in) foo (int aa, int bb) "..." */
  locals = Getattr(tm, "locals");
  if (locals)
    locals = CopyParmList(locals);

  if (pname) {
    if (SwigType_istemplate(pname)) {
      cname = SwigType_namestr(pname);
      pname = cname;
    }
  }
  if (SwigType_istemplate((char *) lname)) {
    clname = SwigType_namestr((char *) lname);
    lname = clname;
  }

  if (mtype && SwigType_isarray(mtype)) {
    num_substitutions = typemap_replace_vars(s, locals, mtype, type, pname, (char *) lname, 1);
  } else {
    num_substitutions = typemap_replace_vars(s, locals, type, type, pname, (char *) lname, 1);
  }
  if (optimal_substitution && num_substitutions > 1) {
    Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE, Getfile(node), Getline(node), "Multiple calls to %s might be generated due to optimal attribute usage in\n", Swig_name_decl(node));
    Swig_warning(WARN_TYPEMAP_OUT_OPTIMAL_MULTIPLE, Getfile(s), Getline(s), "the out typemap.\n");
  }

  if (locals && f) {
    typemap_locals(s, locals, f, -1);
  }

  {
    ParmList *parm_sublist = NewParmWithoutFileLineInfo(type, pname);
    Setattr(parm_sublist, "lname", lname);
    replace_embedded_typemap(s, parm_sublist, f, tm);
    Delete(parm_sublist);
  }

  Replace(s, "$name", pname, DOH_REPLACE_ANY);

  symname = Getattr(node, "sym:name");
  if (symname) {
    Replace(s, "$symname", symname, DOH_REPLACE_ANY);
  }

  Setattr(node, typemap_method_name(tmap_method), s);
  if (locals) {
    sprintf(temp, "%s:locals", cmethod);
    Setattr(node, typemap_method_name(temp), locals);
    Delete(locals);
  }

  if (Checkattr(tm, "type", "SWIGTYPE")) {
    sprintf(temp, "%s:SWIGTYPE", cmethod);
    Setattr(node, typemap_method_name(temp), "1");
  }

  /* Print warnings, if any */
  typemap_warn(cmethod, node);

  /* Look for code fragments */
  {
    String *fragment;
    sprintf(temp, "%s:fragment", cmethod);
    fragment = Getattr(node, typemap_method_name(temp));
    if (fragment) {
      String *fname = Copy(fragment);
      Setfile(fname, Getfile(node));
      Setline(fname, Getline(node));
      Swig_fragment_emit(fname);
      Delete(fname);
    }
  }

  Delete(cname);
  Delete(clname);
  Delete(mtype);
  if (sdef) {			/* put 'ref' and 'newfree' codes together */
    String *p = NewStringf("%s\n%s", sdef, s);
    Delete(s);
    Delete(sdef);
    s = p;
  }
  Delete(actioncode);
  return s;
}

String *Swig_typemap_lookup_out(const_String_or_char_ptr tmap_method, Node *node, const_String_or_char_ptr lname, Wrapper *f, String *actioncode) {
  assert(actioncode);
  assert(Cmp(tmap_method, "out") == 0);
  return Swig_typemap_lookup_impl(tmap_method, node, lname, f, actioncode);
}

String *Swig_typemap_lookup(const_String_or_char_ptr tmap_method, Node *node, const_String_or_char_ptr lname, Wrapper *f) {
  return Swig_typemap_lookup_impl(tmap_method, node, lname, f, 0);
}

/* -----------------------------------------------------------------------------
 * typemap_attach_kwargs()
 *
 * If this hash (tm) contains a linked list of parameters under its "kwargs"
 * attribute, add keys for each of those named keyword arguments to this
 * parameter for later use.
 * For example, attach the typemap attributes to p:
 * %typemap(in, foo="xyz") ...
 * A new attribute called "tmap:in:foo" with value "xyz" is attached to p.
 * ----------------------------------------------------------------------------- */

static void typemap_attach_kwargs(Hash *tm, const_String_or_char_ptr tmap_method, Parm *p) {
  String *temp = NewStringEmpty();
  Parm *kw = Getattr(tm, "kwargs");
  while (kw) {
    String *value = Copy(Getattr(kw, "value"));
    String *type = Getattr(kw, "type");
    if (type) {
      Hash *v = NewHash();
      Setattr(v, "type", type);
      Setattr(v, "value", value);
      Delete(value);
      value = v;
    }
    Clear(temp);
    Printf(temp, "%s:%s", tmap_method, Getattr(kw, "name"));
    Setattr(p, typemap_method_name(temp), value);
    Delete(value);
    kw = nextSibling(kw);
  }
  Clear(temp);
  Printf(temp, "%s:match_type", tmap_method);
  Setattr(p, typemap_method_name(temp), Getattr(tm, "type"));
  Delete(temp);
}

static void typemap_emit_code_fragments(const_String_or_char_ptr tmap_method, Parm *p) {
  String *temp = NewStringf("%s:fragment", tmap_method);
  String *f = Getattr(p, typemap_method_name(temp));
  if (f) {
    String *fname = Copy(f);
    Setfile(fname, Getfile(p));
    Setline(fname, Getline(p));
    Swig_fragment_emit(fname);
    Delete(fname);
  }
  Delete(temp);
}

static String *typemap_get_option(Hash *tm, const_String_or_char_ptr name) {
  Parm *kw = Getattr(tm, "kwargs");
  while (kw) {
    String *kname = Getattr(kw, "name");
    if (Equal(kname, name)) {
      return Getattr(kw, "value");
    }
    kw = nextSibling(kw);
  }
  return 0;
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_attach_parms()
 *
 * Given a parameter list, this function attaches all of the typemaps and typemap
 * attributes to the parameter for each type in the parameter list. 
 *
 * This function basically provides the typemap code and typemap attribute values as
 * attributes on each parameter prefixed with "tmap:". For example with tmap_method="in", the typemap
 * code can be retrieved for the first parameter with a call to Getattr(parm, "tmap:in")
 * and the "numinputs" attribute can be retrieved with a call to Getattr(parm, "tmap:in:numinputs").
 *
 * tmap_method - typemap method, eg "in", "out", "newfree"
 * parms       - parameter list to attach each typemap and all typemap attributes
 * f           - wrapper code to generate into if non null
 * ----------------------------------------------------------------------------- */

void Swig_typemap_attach_parms(const_String_or_char_ptr tmap_method, ParmList *parms, Wrapper *f) {
  Parm *p, *firstp;
  Hash *tm;
  int nmatch = 0;
  int i;
  String *s;
  ParmList *locals;
  int argnum = 0;
  char temp[256];
  char *cmethod = Char(tmap_method);
  String *kwmatch = 0;
  p = parms;

#ifdef SWIG_DEBUG
  Printf(stdout, "Swig_typemap_attach_parms:  %s\n", tmap_method);
#endif

  while (p) {
    argnum++;
    nmatch = 0;
#ifdef SWIG_DEBUG
    Printf(stdout, "parms:  %s %s %s\n", tmap_method, Getattr(p, "name"), Getattr(p, "type"));
#endif
    tm = typemap_search_multi(tmap_method, p, &nmatch);
#ifdef SWIG_DEBUG
    if (tm)
      Printf(stdout, "found:  %s\n", tm);
#endif
    if (!tm) {
      p = nextSibling(p);
      continue;
    }
    /*
       Check if the typemap requires to match the type of another
       typemap, for example:

       %typemap(in) SWIGTYPE * (int var) {...}
       %typemap(freearg,match="in") SWIGTYPE * {if (var$argnum) ...}

       here, the freearg typemap requires the "in" typemap to match,
       or the 'var$argnum' variable will not exist.
     */
    kwmatch = typemap_get_option(tm, "match");
    if (kwmatch) {
      String *tmname = NewStringf("tmap:%s", kwmatch);
      String *tmin = Getattr(p, tmname);
      Delete(tmname);
#ifdef SWIG_DEBUG
      if (tm)
	Printf(stdout, "matching:  %s\n", kwmatch);
#endif
      if (tmin) {
	String *tmninp = NewStringf("tmap:%s:numinputs", kwmatch);
	String *ninp = Getattr(p, tmninp);
	Delete(tmninp);
	if (ninp && Equal(ninp, "0")) {
	  p = nextSibling(p);
	  continue;
	} else {
	  SwigType *typetm = Getattr(tm, "type");
	  String *temp = NewStringf("tmap:%s:match_type", kwmatch);
	  SwigType *typein = Getattr(p, temp);
	  Delete(temp);
	  if (!Equal(typein, typetm)) {
	    p = nextSibling(p);
	    continue;
	  } else {
	    int nnmatch;
	    Hash *tmapin = typemap_search_multi(kwmatch, p, &nnmatch);
	    String *tmname = Getattr(tm, "pname");
	    String *tnname = Getattr(tmapin, "pname");
	    if (!(tmname && tnname && Equal(tmname, tnname)) && !(!tmname && !tnname)) {
	      p = nextSibling(p);
	      continue;
	    }
	  }

	}
      } else {
	p = nextSibling(p);
	continue;
      }
    }

    s = Getattr(tm, "code");
    if (!s) {
      p = nextSibling(p);
      continue;
    }
#ifdef SWIG_DEBUG
    if (s)
      Printf(stdout, "code:  %s\n", s);
#endif

    /* Empty typemap. No match */
    if (Cmp(s, "pass") == 0) {
      p = nextSibling(p);
      continue;
    }

    s = Copy(s);
    locals = Getattr(tm, "locals");
    if (locals)
      locals = CopyParmList(locals);
    firstp = p;
#ifdef SWIG_DEBUG
    Printf(stdout, "nmatch:  %d\n", nmatch);
#endif
    for (i = 0; i < nmatch; i++) {
      SwigType *type;
      String *pname;
      String *lname;
      SwigType *mtype;


      type = Getattr(p, "type");
      pname = Getattr(p, "name");
      lname = Getattr(p, "lname");
      mtype = Getattr(p, "tmap:match");

      if (mtype) {
	typemap_replace_vars(s, locals, mtype, type, pname, lname, i + 1);
	Delattr(p, "tmap:match");
      } else {
	typemap_replace_vars(s, locals, type, type, pname, lname, i + 1);
      }

      if (Checkattr(tm, "type", "SWIGTYPE")) {
	sprintf(temp, "%s:SWIGTYPE", cmethod);
	Setattr(p, typemap_method_name(temp), "1");
      }
      p = nextSibling(p);
    }

    if (locals && f) {
      typemap_locals(s, locals, f, argnum);
    }

    replace_embedded_typemap(s, firstp, f, tm);

    /* Replace the argument number */
    sprintf(temp, "%d", argnum);
    Replace(s, "$argnum", temp, DOH_REPLACE_ANY);

    /* Attach attributes to object */
#ifdef SWIG_DEBUG
    Printf(stdout, "attach: %s %s %s\n", Getattr(firstp, "name"), typemap_method_name(tmap_method), s);
#endif
    Setattr(firstp, typemap_method_name(tmap_method), s);	/* Code object */

    if (locals) {
      sprintf(temp, "%s:locals", cmethod);
      Setattr(firstp, typemap_method_name(temp), locals);
      Delete(locals);
    }

    /* Attach a link to the next parameter.  Needed for multimaps */
    sprintf(temp, "%s:next", cmethod);
    Setattr(firstp, typemap_method_name(temp), p);

    /* Attach kwargs */
    typemap_attach_kwargs(tm, tmap_method, firstp);

    /* Print warnings, if any */
    typemap_warn(tmap_method, firstp);

    /* Look for code fragments */
    typemap_emit_code_fragments(tmap_method, firstp);

    /* increase argnum to consider numinputs */
    argnum += nmatch - 1;
    Delete(s);
#ifdef SWIG_DEBUG
    Printf(stdout, "res: %s %s %s\n", Getattr(firstp, "name"), typemap_method_name(tmap_method), Getattr(firstp, typemap_method_name(tmap_method)));
#endif

  }
#ifdef SWIG_DEBUG
  Printf(stdout, "Swig_typemap_attach_parms: end\n");
#endif

}

/* Splits the arguments of an embedded typemap */
static List *split_embedded_typemap(String *s) {
  List *args = 0;
  char *c, *start;
  int level = 0;
  int angle_level = 0;
  int leading = 1;

  args = NewList();
  c = strchr(Char(s), '(');
  assert(c);
  c++;

  start = c;
  while (*c) {
    if (*c == '\"') {
      c++;
      while (*c) {
	if (*c == '\\') {
	  c++;
	} else {
	  if (*c == '\"')
	    break;
	}
	c++;
      }
    }
    if ((level == 0) && angle_level == 0 && ((*c == ',') || (*c == ')'))) {
      String *tmp = NewStringWithSize(start, c - start);
      Append(args, tmp);
      Delete(tmp);
      start = c + 1;
      leading = 1;
      if (*c == ')')
	break;
      c++;
      continue;
    }
    if (*c == '(')
      level++;
    if (*c == ')')
      level--;
    if (*c == '<')
      angle_level++;
    if (*c == '>')
      angle_level--;
    if (isspace((int) *c) && leading)
      start++;
    if (!isspace((int) *c))
      leading = 0;
    c++;
  }
  return args;
}

/* -----------------------------------------------------------------------------
 * replace_embedded_typemap()
 *
 * This function replaces the special variable macro $typemap(...) with typemap
 * code. The general form of $typemap is as follows:
 *
 *   $typemap(method, typelist, var1=value, var2=value, ...)
 *
 * where varx parameters are optional and undocumented; they were used in an earlier version of $typemap.
 * A search is made using the typemap matching rules of form:
 *
 *   %typemap(method) typelist {...}
 *
 * and if found will substitute in the typemap contents, making appropriate variable replacements.
 *
 * For example:
 *   $typemap(in, int)			     # simple usage matching %typemap(in) int { ... }
 *   $typemap(in, int b)		     # simple usage matching %typemap(in) int b { ... } or above %typemap
 *   $typemap(in, (Foo<int, bool> a, int b)) # multi-argument typemap matching %typemap(in) (Foo<int, bool> a, int b) {...}
 * ----------------------------------------------------------------------------- */

static void replace_embedded_typemap(String *s, ParmList *parm_sublist, Wrapper *f, Node *file_line_node) {
  char *start = 0;
  while ((start = strstr(Char(s), "$TYPEMAP("))) { /* note $typemap capitalisation to $TYPEMAP hack */

    /* Gather the parameters */
    char *end = 0, *c;
    int level = 0;
    String *dollar_typemap;
    int syntax_error = 1;
    c = start;
    while (*c) {
      if (*c == '(')
	level++;
      if (*c == ')') {
	level--;
	if (level == 0) {
	  end = c + 1;
	  break;
	}
      }
      c++;
    }
    if (end) {
      dollar_typemap = NewStringWithSize(start, (end - start));
      syntax_error = 0;
    } else {
      dollar_typemap = NewStringWithSize(start, (c - start));
    }

    if (!syntax_error) {
      List *l;
      String *tmap_method;
      Hash *vars;
      syntax_error = 1;

      /* Split apart each parameter in $typemap(...) */
      l = split_embedded_typemap(dollar_typemap);

      if (Len(l) >= 2) {
	ParmList *to_match_parms;
	tmap_method = Getitem(l, 0);

	/* the second parameter might contain multiple sub-parameters for multi-argument 
	 * typemap matching, so split these parameters apart */
	to_match_parms = Swig_cparse_parms(Getitem(l, 1), file_line_node);
	if (to_match_parms) {
	  Parm *p = to_match_parms;
	  Parm *sub_p = parm_sublist;
	  String *empty_string = NewStringEmpty(); 
	  String *lname = empty_string;
	  while (p) {
	    if (sub_p) {
	      lname = Getattr(sub_p, "lname");
	      sub_p = nextSibling(sub_p);
	    }
	    Setattr(p, "lname", lname);
	    p = nextSibling(p);
	  }
	  Delete(empty_string);
	}

	/* process optional extra parameters - the variable replacements (undocumented) */
	vars = NewHash();
	{
	  int i, ilen;
	  ilen = Len(l);
	  for (i = 2; i < ilen; i++) {
	    String *parm = Getitem(l, i);
	    char *eq = strchr(Char(parm), '=');
	    char *c = Char(parm);
	    if (eq && (eq - c > 0)) {
	      String *name = NewStringWithSize(c, eq - c);
	      String *value = NewString(eq + 1);
	      Insert(name, 0, "$");
	      Setattr(vars, name, value);
	    } else {
	      to_match_parms = 0; /* error - variable replacement parameters must be of form varname=value */
	    }
	  }
	}

	/* Perform a typemap search */
	if (to_match_parms) {
	  static int already_substituting = 0;
	  String *tm;
	  String *attr;
	  int match = 0;
#ifdef SWIG_DEBUG
	  Printf(stdout, "Swig_typemap_attach_parms:  embedded\n");
#endif
	  if (already_substituting < 10) {
	    already_substituting++;
	    if ((in_typemap_search_multi == 0) && typemap_search_debug) {
	      String *dtypemap = NewString(dollar_typemap);
	      Replaceall(dtypemap, "$TYPEMAP", "$typemap");
	      Printf(stdout, "  Containing: %s\n", dtypemap);
	      Delete(dtypemap);
	    }
	    Swig_typemap_attach_parms(tmap_method, to_match_parms, f);
	    already_substituting--;

	    /* Look for the typemap code */
	    attr = NewStringf("tmap:%s", tmap_method);
	    tm = Getattr(to_match_parms, attr);
	    if (tm) {
	      Printf(attr, "%s", ":next");
	      /* fail if multi-argument lookup requested in $typemap(...) and the lookup failed */
	      if (!Getattr(to_match_parms, attr)) {
		/* Replace parameter variables */
		Iterator ki;
		for (ki = First(vars); ki.key; ki = Next(ki)) {
		  Replace(tm, ki.key, ki.item, DOH_REPLACE_ANY);
		}
		/* offer the target language module the chance to make special variable substitutions */
		Language_replace_special_variables(tmap_method, tm, to_match_parms);
		/* finish up - do the substitution */
		Replace(s, dollar_typemap, tm, DOH_REPLACE_ANY);
		Delete(tm);
		match = 1;
	      }
	    }

	    if (!match) {
	      String *dtypemap = NewString(dollar_typemap);
	      Replaceall(dtypemap, "$TYPEMAP", "$typemap");
	      Swig_error(Getfile(s), Getline(s), "No typemap found for %s\n", dtypemap);
	      Delete(dtypemap);
	    }
	    Delete(attr);
	  } else {
	    /* Simple recursive call check to prevent infinite recursion - this strategy only allows a limited 
	     * number of calls by a embedded typemaps to other embedded typemaps though */
	    String *dtypemap = NewString(dollar_typemap);
	    Replaceall(dtypemap, "$TYPEMAP", "$typemap");
	    Swig_error(Getfile(s), Getline(s), "Likely recursive $typemap calls containing %s. Use -debug-tmsearch to debug.\n", dtypemap);
	    Delete(dtypemap);
	  }
	  syntax_error = 0;
	}
	Delete(vars);
      }
      Delete(l);
    }

    if (syntax_error) {
      String *dtypemap = NewString(dollar_typemap);
      Replaceall(dtypemap, "$TYPEMAP", "$typemap");
      Swig_error(Getfile(s), Getline(s), "Syntax error in: %s\n", dtypemap);
      Delete(dtypemap);
    }
    Replace(s, dollar_typemap, "<error in embedded typemap>", DOH_REPLACE_ANY);
    Delete(dollar_typemap);
  }
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_debug()
 *
 * Display all typemaps
 * ----------------------------------------------------------------------------- */

void Swig_typemap_debug() {
  int ts;
  Printf(stdout, "---[ typemaps ]--------------------------------------------------------------\n");

  ts = tm_scope;
  while (ts >= 0) {
    Printf(stdout, "::: scope %d\n\n", ts);
    Printf(stdout, "%s\n", typemaps[ts]);
    ts--;
  }
  Printf(stdout, "-----------------------------------------------------------------------------\n");
}


/* -----------------------------------------------------------------------------
 * Swig_typemap_search_debug_set()
 *
 * Turn on typemap searching debug display
 * ----------------------------------------------------------------------------- */

void Swig_typemap_search_debug_set(void) {
  typemap_search_debug = 1;
}

/* -----------------------------------------------------------------------------
 * Swig_typemap_used_debug_set()
 *
 * Turn on typemaps used debug display
 * ----------------------------------------------------------------------------- */

void Swig_typemap_used_debug_set(void) {
  typemaps_used_debug = 1;
}