[go: up one dir, main page]

File: attributes.cpp

package info (click to toggle)
rcpp 0.11.3-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 9,948 kB
  • ctags: 16,427
  • sloc: ansic: 42,692; cpp: 34,078; makefile: 32; sh: 21
file content (2983 lines) | stat: -rw-r--r-- 107,387 bytes parent folder | download
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
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
//
// attributes.cpp: Rcpp R/C++ interface class library -- Rcpp attributes
//
// Copyright (C) 2012 - 2013 JJ Allaire, Dirk Eddelbuettel and Romain Francois
//
// This file is part of Rcpp.
//
// Rcpp is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Rcpp is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.

#define COMPILING_RCPP

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#include <cstring>

#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <sstream>

#define RCPP_NO_SUGAR
#include <Rcpp.h>

/*******************************************************************
 * AttributesUtil.h
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    // Utility class for getting file existence and last modified time
    class FileInfo {
    public:
        explicit FileInfo(const std::string& path);

        std::string path() const { return path_; }
        bool exists() const { return exists_; }
        time_t lastModified() const { return lastModified_; }

    private:
        std::string path_;
        bool exists_;
        time_t lastModified_;
    };

    // Remove a file
    bool removeFile(const std::string& path);

    // Recursively create a directory
    void createDirectory(const std::string& path);

    // Known whitespace chars
    extern const char * const kWhitespaceChars;

    // Query whether a character is whitespace
    bool isWhitespace(char ch);

    // Trim a string
    void trimWhitespace(std::string* pStr);

    // Strip trailing line comments
    void stripTrailingLineComments(std::string* pStr);

    // Strip balanced quotes from around a string (assumes already trimmed)
    void stripQuotes(std::string* pStr);

    // is the passed string quoted?
    bool isQuoted(const std::string& str);

    // show a warning message
    void showWarning(const std::string& msg);

    // is the line a C++ roxygen comment? (started with //')
    bool isRoxygenCpp(const std::string& str);

} // namespace attributes
} // namespace Rcpp


/*******************************************************************
 * AttributesTypes.h
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    // Known attribute names & parameters
    const char * const kExportAttribute = "export";
    const char * const kDependsAttribute = "depends";
    const char * const kPluginsAttribute = "plugins";
    const char * const kInterfacesAttribute = "interfaces";
    const char * const kInterfaceR = "r";
    const char * const kInterfaceCpp = "cpp";

    // Type info
    class Type {
    public:
        Type() {}
        Type(const std::string& name, bool isConst, bool isReference)
            : name_(name), isConst_(isConst), isReference_(isReference)
        {
        }
        bool empty() const { return name().empty(); }

        const std::string& name() const { return name_; }
        std::string full_name() const {
            std::string res ;
            if( isConst() ) res += "const " ;
            res += name() ;
            if( isReference() ) res += "&" ;
            return res ;
        }

        bool isVoid() const { return name() == "void"; }
        bool isConst() const { return isConst_; }
        bool isReference() const { return isReference_; }

    private:
        std::string name_;
        bool isConst_;
        bool isReference_;
    };

    // Argument info
    class Argument {
    public:
        Argument() {}
        Argument(const std::string& name,
                 const Type& type,
                 const std::string& defaultValue)
            : name_(name), type_(type), defaultValue_(defaultValue)
        {
        }

        bool empty() const { return type().empty(); }

        const std::string& name() const { return name_; }
        const Type& type() const { return type_; }
        const std::string& defaultValue() const { return defaultValue_; }

    private:
        std::string name_;
        Type type_;
        std::string defaultValue_;
    };

    // Function info
    class Function {
    public:
        Function() {}
        Function(const Type& type,
                 const std::string& name,
                 const std::vector<Argument>& arguments,
                 const std::string& source)
            : type_(type), name_(name), arguments_(arguments), source_(source)
        {
        }

        Function renamedTo(const std::string& name) const {
            return Function(type(), name, arguments(), source());
        }

        std::string signature() const { return signature(name()); }
        std::string signature(const std::string& name) const;

        bool isHidden() const {
            return name().find_first_of('.') == 0;
        }

        bool empty() const { return name().empty(); }

        const Type& type() const { return type_; }
        const std::string& name() const { return name_; }
        const std::vector<Argument>& arguments() const { return arguments_; }
        const std::string& source() const { return source_; }

    private:
        Type type_;
        std::string name_;
        std::vector<Argument> arguments_;
        std::string source_;
    };

    // Attribute parameter (with optional value)
    class Param {
    public:
        Param() {}
        explicit Param(const std::string& paramText);
        bool empty() const { return name().empty(); }

        const std::string& name() const { return name_; }
        const std::string& value() const { return value_; }

    private:
        std::string name_;
        std::string value_;
    };

    // Attribute (w/ optional params and signature of function it qualifies)
    class Attribute {
    public:
        Attribute() {}
        Attribute(const std::string& name,
                  const std::vector<Param>& params,
                  const Function& function,
                  const std::vector<std::string>& roxygen)
            : name_(name), params_(params), function_(function), roxygen_(roxygen)
        {
        }

        bool empty() const { return name().empty(); }

        const std::string& name() const { return name_; }

        const std::vector<Param>& params() const { return params_; }

        Param paramNamed(const std::string& name) const;

        bool hasParameter(const std::string& name) const {
            return !paramNamed(name).empty();
        }

        const Function& function() const { return function_; }

        bool isExportedFunction() const {
            return (name() == kExportAttribute) && !function().empty();
        }

        std::string exportedName() const {
            if (!params().empty())
                return params()[0].name();
            else
                return function().name();
        }

        const std::vector<std::string>& roxygen() const { return roxygen_; }

    private:
        std::string name_;
        std::vector<Param> params_;
        Function function_;
        std::vector<std::string> roxygen_;
    };

    class FunctionMap {
        std::map< std::string, std::vector<Function> > map_ ;

    public:
        FunctionMap(){};
        ~FunctionMap(){} ;

        void insert( const Function& fun ){
            map_[ fun.name() ].push_back( fun ) ;
        }
    } ;

    // Operator << for parsed types
    std::ostream& operator<<(std::ostream& os, const Type& type);
    std::ostream& operator<<(std::ostream& os, const Argument& argument);
    std::ostream& operator<<(std::ostream& os, const Function& function);
    std::ostream& operator<<(std::ostream& os, const Param& param);
    std::ostream& operator<<(std::ostream& os, const Attribute& attribute);

    // interface to source file attributes
    class SourceFileAttributes
    {
    public:
        virtual ~SourceFileAttributes() {};
        virtual const std::string& sourceFile() const = 0;
        virtual bool hasInterface(const std::string& name) const = 0;

        typedef std::vector<Attribute>::const_iterator const_iterator;
        virtual const_iterator begin() const = 0;
        virtual const_iterator end() const = 0;

        virtual const std::vector<std::string>& modules() const = 0;

        virtual const std::vector<std::vector<std::string> >& roxygenChunks() const = 0;

        virtual bool hasGeneratorOutput() const = 0;
    };


} // namespace attributes
} // namespace Rcpp



/*******************************************************************
 * AttributesParser.h
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    // Helper class for determining whether we are in a comment
    class CommentState {
    public:
        CommentState() : inComment_(false) {}
    private:
        // prohibit copying
        CommentState(const CommentState&);
        CommentState& operator=(const CommentState&);
    public:
        bool inComment() const { return inComment_; }
        void submitLine(const std::string& line);
        void reset() { inComment_ = false; }
    private:
        bool inComment_;
    };

    // Class used to parse and return attribute information from a source file
    class SourceFileAttributesParser : public SourceFileAttributes {
    public:
        explicit SourceFileAttributesParser(const std::string& sourceFile);

    private:
        // prohibit copying
        SourceFileAttributesParser(const SourceFileAttributesParser&);
        SourceFileAttributesParser& operator=(const SourceFileAttributesParser&);

    public:
        // implemetnation of SourceFileAttributes interface
        virtual const std::string& sourceFile() const {
            return sourceFile_;
        }
        virtual const_iterator begin() const { return attributes_.begin(); }
        virtual const_iterator end() const { return attributes_.end(); }

        virtual const std::vector<std::string>& modules() const
        {
            return modules_;
        }

        virtual const std::vector<std::vector<std::string> >& roxygenChunks() const {
            return roxygenChunks_;
        }

        virtual bool hasGeneratorOutput() const
        {
            return !attributes_.empty() ||
                   !modules_.empty() ||
                   !roxygenChunks_.empty();
        }

        virtual bool hasInterface(const std::string& name) const {

            for (const_iterator it=begin(); it != end(); ++it) {
                if (it->name() == kInterfacesAttribute) {
                    return it->hasParameter(name);
                }
            }

            // if there's no interfaces attrbute we default to R
            if (name == kInterfaceR)
                return true;
            else
                return false;
        }

        // Get lines of embedded R code
        const std::vector<std::string>& embeddedR() const {
            return embeddedR_;
        }

    private:

        // Parsing helpers
        Attribute parseAttribute(const std::vector<std::string>& match,
                                 int lineNumber);
        std::vector<Param> parseParameters(const std::string& input);
        Function parseFunction(size_t lineNumber);
        std::string parseSignature(size_t lineNumber);
        std::vector<std::string> parseArguments(const std::string& argText);
        Type parseType(const std::string& text);

        // Validation helpers
        bool isKnownAttribute(const std::string& name) const;
        void attributeWarning(const std::string& message,
                              const std::string& attribute,
                              size_t lineNumber);
        void attributeWarning(const std::string& message, size_t lineNumber);
        void rcppExportWarning(const std::string& message, size_t lineNumber);
        void rcppExportNoFunctionFoundWarning(size_t lineNumber);
        void rcppExportInvalidParameterWarning(const std::string& param,
                                               size_t lineNumber);
        void rcppInterfacesWarning(const std::string& message,
                                   size_t lineNumber);

    private:
        std::string sourceFile_;
        CharacterVector lines_;
        std::vector<Attribute> attributes_;
        FunctionMap functionMap_ ;
        std::vector<std::string> modules_;
        std::vector<std::string> embeddedR_;
        std::vector<std::vector<std::string> > roxygenChunks_;
        std::vector<std::string> roxygenBuffer_;
    };

} // namespace attributes
} // namespace Rcpp


/*******************************************************************
 * AttributesGen.h
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    // Abstract class which manages writing of code for compileAttributes
    class ExportsGenerator {
    protected:
        ExportsGenerator(const std::string& targetFile,
                         const std::string& package,
                         const std::string& commentPrefix);

    private:
        // prohibit copying
        ExportsGenerator(const ExportsGenerator&);
        ExportsGenerator& operator=(const ExportsGenerator&);

    public:
        virtual ~ExportsGenerator() {}

        // Name of target file and package
        const std::string& targetFile() const { return targetFile_; }
        const std::string& package() const { return package_; }

        // Abstract interface for code generation
        virtual void writeBegin() = 0;
        void writeFunctions(const SourceFileAttributes& attributes,
                            bool verbose); // see doWriteFunctions below
        virtual void writeEnd() = 0;

        virtual bool commit(const std::vector<std::string>& includes) = 0;

        // Remove the generated file entirely
        bool remove();

        // Allow generator to appear as a std::ostream&
        operator std::ostream&() {
            return codeStream_;
        }

    protected:

        // Allow access to the output stream
        std::ostream& ostr() {
            return codeStream_;
        }

        bool hasCppInterface() const {
            return hasCppInterface_;
        }

        // Shared knowledge about function namees
        std::string exportValidationFunction() {
            return "RcppExport_validate";
        }
        std::string exportValidationFunctionRegisteredName() {
            return package() + "_" + exportValidationFunction();
        }
        std::string registerCCallableExportedName() {
            return package() + "_RcppExport_registerCCallable";
        }

        // Commit the stream -- is a no-op if the existing code is identical
        // to the generated code. Returns true if data was written and false
        // if it wasn't (throws exception on io error)
        bool commit(const std::string& preamble = std::string());

    private:

        // Private virtual for doWriteFunctions so the base class
        // can always intercept writeFunctions
        virtual void doWriteFunctions(const SourceFileAttributes& attributes,
                                      bool verbose) = 0;

        // Check whether it's safe to overwrite this file (i.e. whether we
        // generated the file in the first place)
        bool isSafeToOverwrite() const {
            return existingCode_.empty() ||
                   (existingCode_.find(generatorToken()) != std::string::npos);
        }

        // UUID that we write into a comment within the file (so that we can
        // strongly identify that a file was generated by us before overwriting it)
        std::string generatorToken() const {
            return "10BE3573-1514-4C36-9D1C-5A225CD40393";
        }

    private:
        std::string targetFile_;
        std::string package_;
        std::string commentPrefix_;
        std::string existingCode_;
        std::ostringstream codeStream_;
        bool hasCppInterface_;
    };

    // Class which manages generating RcppExports.cpp
    class CppExportsGenerator : public ExportsGenerator {
    public:
        explicit CppExportsGenerator(const std::string& packageDir,
                                     const std::string& package,
                                     const std::string& fileSep);

        virtual void writeBegin() {};
        virtual void writeEnd();
        virtual bool commit(const std::vector<std::string>& includes);

    private:
        virtual void doWriteFunctions(const SourceFileAttributes& attributes,
                                      bool verbose);

        std::string registerCCallable(size_t indent,
                                      const std::string& exportedName,
                                      const std::string& name) const;

    private:
        std::vector<Attribute> cppExports_;
    };

    // Class which manages generating PackageName_RcppExports.h header file
    class CppExportsIncludeGenerator : public ExportsGenerator {
    public:
        CppExportsIncludeGenerator(const std::string& packageDir,
                                   const std::string& package,
                                   const std::string& fileSep);

        virtual void writeBegin();
        virtual void writeEnd();
        virtual bool commit(const std::vector<std::string>& includes);

    private:
        virtual void doWriteFunctions(const SourceFileAttributes& attributes,
                                      bool verbose);
        std::string getCCallable(const std::string& function) const;
        std::string getHeaderGuard() const;

    private:
        std::string includeDir_;
    };

    // Class which manages generating PackageName_RcppExports.h header file
    class CppPackageIncludeGenerator : public ExportsGenerator {
    public:
        CppPackageIncludeGenerator(const std::string& packageDir,
                                   const std::string& package,
                                   const std::string& fileSep);

        virtual void writeBegin() {}
        virtual void writeEnd();
        virtual bool commit(const std::vector<std::string>& includes);

    private:
        virtual void doWriteFunctions(const SourceFileAttributes& attributes,
                                      bool verbose) {}
        std::string getHeaderGuard() const;

    private:
        std::string includeDir_;
    };


    // Class which manages generator RcppExports.R
    class RExportsGenerator : public ExportsGenerator {
    public:
        RExportsGenerator(const std::string& packageDir,
                          const std::string& package,
                          const std::string& fileSep);

        virtual void writeBegin() {}
        virtual void writeEnd();
        virtual bool commit(const std::vector<std::string>& includes);

    private:
        virtual void doWriteFunctions(const SourceFileAttributes& attributes,
                                      bool verbose);

    };

    // Class to manage and dispatch to a list of generators
    class ExportsGenerators {
    public:
        typedef std::vector<ExportsGenerator*>::iterator Itr;

        ExportsGenerators() {}
        virtual ~ExportsGenerators();

        void add(ExportsGenerator* pGenerator);

        void writeBegin();
        void writeFunctions(const SourceFileAttributes& attributes,
                            bool verbose);
        void writeEnd();

        // Commit and return a list of the files that were updated
        std::vector<std::string> commit(
                                const std::vector<std::string>& includes);

        // Remove and return a list of files that were removed
        std::vector<std::string> remove();

    private:
        // prohibit copying
        ExportsGenerators(const ExportsGenerators&);
        ExportsGenerators& operator=(const ExportsGenerators&);

    private:
        std::vector<ExportsGenerator*> generators_;
    };

    // Standalone generation helpers (used by sourceCpp)

    std::string generateRArgList(const Function& function);

    void generateCpp(std::ostream& ostr,
                     const SourceFileAttributes& attributes,
                     bool includePrototype,
                     bool cppInterface,
                     const std::string& contextId);

} // namespace attributes
} // namespace Rcpp


/*******************************************************************
 * AttributesParser.cpp
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    namespace {

        Rcpp::List regexMatches(Rcpp::CharacterVector lines,
                                const std::string& regex)
        {
            Rcpp::Environment base("package:base");
            Rcpp::Function regexec = base["regexec"];
            Rcpp::Function regmatches = base["regmatches"];
            Rcpp::RObject result =  regexec(regex, lines);
            Rcpp::List matches = regmatches(lines, result);
            return matches;
        }

        // Parse embedded R code chunks from a file (receives the lines of the
        // file as a CharcterVector for using with regexec and as a standard
        // stl vector for traversal/insepection)
        std::vector<std::string> parseEmbeddedR(
                                        Rcpp::CharacterVector linesVector,
                                        const std::deque<std::string>& lines) {
            Rcpp::List matches = regexMatches(linesVector,
                                              "^\\s*/\\*{3,}\\s+[Rr]\\s*$");
            bool withinRBlock = false;
            CommentState commentState;
            std::vector<std::string> embeddedR;

            for (int i = 0; i<matches.size(); i++) {

                // track comment state
                std::string line = lines[i];
                commentState.submitLine(line);

                // is this a line that begins an R code block?
                const Rcpp::CharacterVector match = matches[i];
                bool beginRBlock = match.size() > 0;

                // check state and do the right thing
                if (beginRBlock) {
                    withinRBlock = true;
                }
                else if (withinRBlock) {
                    if (commentState.inComment())
                        embeddedR.push_back(line);
                    else
                        withinRBlock = false;
                }
            }

            return embeddedR;
        }

    } // anonymous namespace


    // Generate a type signature for the function with the provided name
    // (type signature == function pointer declaration)
    std::string Function::signature(const std::string& name) const {

        std::ostringstream ostr;

        ostr << type() << "(*" << name << ")(";

        const std::vector<Argument>& args = arguments();
        for (std::size_t i = 0; i<args.size(); i++) {
            ostr << args[i].type();
            if (i != (args.size()-1))
                ostr << ",";
        }
        ostr << ")";

        return ostr.str();
    }


    // Parse attribute parameter from parameter text
    Param::Param(const std::string& paramText)
    {
        // parse out name/value pair if there is one
        std::string::size_type pos = paramText.find("=") ;
        if ( pos != std::string::npos ) {
            // name
            name_ = paramText.substr(0, pos);
            trimWhitespace(&name_);
            // value
            value_ = paramText.substr(pos + 1) ;
            trimWhitespace(&value_);
            stripQuotes(&value_);
        }
        else {
            name_ = paramText;
            stripQuotes(&name_);
        }
    }

    // Check if the attribute has a parameter of a paricular name
    Param Attribute::paramNamed(const std::string& name) const {
        for (std::vector<Param>::const_iterator
          it = params_.begin(); it != params_.end(); ++it) {
            if (it->name() == name)
                return *it;
        }
        return Param();
    }

    // Type operator <<
    std::ostream& operator<<(std::ostream& os, const Type& type) {
        if (!type.empty()) {
            if (type.isConst())
                os << "const ";
            os << type.name();
            if (type.isReference())
                os << "&";
        }
        return os;
    }

    // Argument operator <<
    std::ostream& operator<<(std::ostream& os, const Argument& argument) {
        if (!argument.empty()) {
            os << argument.type();
            if (!argument.name().empty()) {
                os << " ";
                os << argument.name();
                if (!argument.defaultValue().empty())
                    os << " = " << argument.defaultValue();
            }
        }
        return os;
    }

    // Function operator <<
    std::ostream& operator<<(std::ostream& os, const Function& function) {
        if (!function.empty()) {
            if (!function.type().empty()) {
                os << function.type();
                os << " ";
            }
            os << function.name();
            os << "(";
            const std::vector<Argument>& arguments = function.arguments();
            for (std::size_t i = 0; i<arguments.size(); i++) {
                os << arguments[i];
                if (i != (arguments.size()-1))
                    os << ", ";
            }
            os << ")";
        }
        return os;
    }

    // Param operator <<
    std::ostream& operator<<(std::ostream& os, const Param& param) {
        if (!param.empty()) {
            os << param.name();
            if (!param.value().empty())
                os << "=" << param.value();
        }
        return os;
    }

    // Attribute operator <<
    std::ostream& operator<<(std::ostream& os, const Attribute& attribute) {
        if (!attribute.empty()) {
            os << "[[Rcpp::" << attribute.name();
            const std::vector<Param>& params = attribute.params();
            if (params.size() > 0) {
                os << "(";
                for (std::size_t i = 0; i<params.size(); i++) {
                    os << params[i];
                    if (i != (params.size()-1))
                        os << ",";
                }
                os << ")";
            }
            os << "]]";

            if (!attribute.function().empty())
                os << " " << attribute.function();
        }
        return os;
    }

    // Parse the attributes from a source file
    SourceFileAttributesParser::SourceFileAttributesParser
                                            (const std::string& sourceFile)
        : sourceFile_(sourceFile)
    {
        // First read the entire file into a std::stringstream so we can check
        // it for attributes (we don't want to do any of our more expensive
        // processing steps if there are no attributes to parse)
        std::ifstream ifs(sourceFile_.c_str());
        if (ifs.fail())
            throw Rcpp::file_io_error(sourceFile_);
        std::stringstream buffer;
        buffer << ifs.rdbuf();
        std::string contents = buffer.str();

        // Check for attribute signature
        if (contents.find("[[Rcpp::") != std::string::npos ||
            contents.find("RCPP_MODULE") != std::string::npos) {

            // Now read into a list of strings (which we can pass to regexec)
            // First read into a std::deque (which will handle lots of append
            // operations efficiently) then copy into an R chracter vector
            std::string line;
            std::deque<std::string> lines;
            while(std::getline(buffer, line)) {
                // strip \r (for the case of windows line terminators on posix)
                if (line.length() > 0 && *line.rbegin() == '\r')
                    line.erase(line.length()-1, 1);
                stripTrailingLineComments(&line);
                lines.push_back(line);
            }
            lines_ = Rcpp::wrap(lines);

            // Scan for attributes
            CommentState commentState;
            Rcpp::List matches = regexMatches(lines_,
                "^\\s*//\\s*\\[\\[Rcpp::(\\w+)(\\(.*?\\))?\\]\\]\\s*$");
            for (int i = 0; i<matches.size(); i++) {

                // track whether we are in a comment and bail if we are in one
                std::string line = lines[i];
                commentState.submitLine(line);
                if (commentState.inComment())
                    continue;

                // attribute line
                const Rcpp::CharacterVector match = matches[i];
                if (match.size() > 0) {

                    // if the match size isn't 3 then regmatches has not behaved
                    // as expected (it should return a vector of either 0 or 3
                    // elements). we don't ever expect this to occur but if it
                    // does let's not crash
                    if (match.size() != 3)
                        continue;

                    // add the attribute
                    Attribute attr = parseAttribute(
                        Rcpp::as<std::vector<std::string> >(match),  i);
                    attributes_.push_back(attr);

                    if( attr.isExportedFunction() ){
                        functionMap_.insert(attr.function());
                    }
                }

                // if it's not an attribute line then it could still be a
                // line of interest (e.g. roxygen comment)
                else {

                    // save roxygen comments
                    if (line.find("//'") == 0) {
                        std::string roxLine = "#" + line.substr(2);
                        roxygenBuffer_.push_back(roxLine);
                    }

                    // a non-roxygen line causes us to clear the roxygen buffer
                    else if (!roxygenBuffer_.empty()) {
                        roxygenChunks_.push_back(roxygenBuffer_);
                        roxygenBuffer_.clear();
                    }
                }
            }

            // Scan for Rcpp modules
            commentState.reset();
            Rcpp::List modMatches = regexMatches(lines_,
                "^\\s*RCPP_MODULE\\s*\\(\\s*(\\w+)\\s*\\).*$");
            for (int i = 0; i<modMatches.size(); i++) {

                // track whether we are in a comment and bail if we are in one
                std::string line = lines[i];
                commentState.submitLine(line);
                if (commentState.inComment())
                    continue;

                // get the module declaration
                Rcpp::CharacterVector match = modMatches[i];
                if (match.size() > 0) {
                    const char * name = match[1];
                    modules_.push_back(name);
                }
            }

            // Parse embedded R
            embeddedR_ = parseEmbeddedR(lines_, lines);
        }
    }

    // Parse an attribute from the vector returned by regmatches
    Attribute SourceFileAttributesParser::parseAttribute(
                                    const std::vector<std::string>& match,
                                    int lineNumber) {

        // Attribute name
        std::string name = match[1];

        // Warn if this is an unknown attribute
        if (!isKnownAttribute(name)) {
            attributeWarning("Unrecognized attribute Rcpp::" + name,
                             lineNumber);
        }

        // Extract params if we've got them
        std::vector<Param> params;
        std::string paramsText = match[2];
        if (!paramsText.empty()) {

            // we know from the regex that it's enclosed in parens so remove
            // trim before we do this just in case someone updates the regex
            // to allow for whitespace around the call
            trimWhitespace(&paramsText);

            paramsText = paramsText.substr(1, paramsText.size()-2);

            // parse the parameters
            params = parseParameters(paramsText);
        }

        // Extract function signature if this is a function attribute
        // and it doesn't appear at the end of the file
        Function function;

        // special handling for export
        if (name == kExportAttribute) {

            // parse the function (unless we are at the end of the file in
            // which case we print a warning)
            if ((lineNumber + 1) < lines_.size())
                function = parseFunction(lineNumber + 1);
            else
                rcppExportWarning("No function found", lineNumber);
        }

        // validate interfaces parameter
        else if (name == kInterfacesAttribute) {
            if (params.empty()) {
                rcppInterfacesWarning("No interfaces specified", lineNumber);
            }
            else {
                for (std::size_t i=0; i<params.size(); i++) {
                    std::string param = params[i].name();
                    if (param != kInterfaceR && param != kInterfaceCpp) {
                        rcppInterfacesWarning(
                            "Unknown interface '" + param + "'", lineNumber);
                    }
                }
            }


        }

        // Return attribute
        Attribute attribute = Attribute(name, params, function, roxygenBuffer_);
        roxygenBuffer_.clear();
        return attribute;
    }

    // Parse attribute parameters
    std::vector<Param> SourceFileAttributesParser::parseParameters(
                                                    const std::string& input) {

        const std::string delimiters(" ,");

        std::vector<Param> params;
        std::string::size_type current;
        std::string::size_type next = -1;
        do {
            next = input.find_first_not_of(delimiters, next + 1);
            if (next == std::string::npos)
                break;
            next -= 1;
            current = next + 1;
            next = input.find_first_of(delimiters, current);
            params.push_back(Param(input.substr(current, next - current)));
        } while(next != std::string::npos);

        return params;
    }

    // Parse a function from the specified spot in the source file
    Function SourceFileAttributesParser::parseFunction(size_t lineNumber) {

        // Establish the text to parse for the signature
        std::string signature = parseSignature(lineNumber);
        if (signature.empty()) {
            rcppExportNoFunctionFoundWarning(lineNumber);
            return Function();
        }

        // Start at the end and look for the () that deliniates the arguments
        // (bail with an empty result if we can't find them)
        std::string::size_type endParenLoc = signature.find_last_of(')');
        std::string::size_type beginParenLoc = signature.find_first_of('(');
        if (endParenLoc == std::string::npos ||
            beginParenLoc == std::string::npos ||
            endParenLoc < beginParenLoc) {

            rcppExportNoFunctionFoundWarning(lineNumber);
            return Function();
        }

        // Find the type and name by scanning backwards for the whitespace that
        // delimites the type and name
        Type type;
        std::string name;
        const std::string preambleText = signature.substr(0, beginParenLoc);
        for (std::string::const_reverse_iterator
            it = preambleText.rbegin(); it != preambleText.rend(); ++it) {
            char ch = *it;
            if (isWhitespace(ch)) {
                if (!name.empty()) {
                    // we are at the break between type and name so we can also
                    // extract the type
                    std::string typeText;
                    while (++it != preambleText.rend())
                        typeText.insert(0U, 1U, *it);
                    type = parseType(typeText);

                    // break (since we now have the name and the type)
                    break;
                }
                else
                    continue;
            } else {
                name.insert(0U, 1U, ch);
            }
        }

        // If we didn't find a name then bail
        if (name.empty()) {
            rcppExportNoFunctionFoundWarning(lineNumber);
            return Function();
        }

        // If we didn't find a type then bail
        if (type.empty()) {
            rcppExportWarning("No function return type found", lineNumber);
            return Function();
        }

        // Now scan for arguments
        std::vector<Argument> arguments;
        std::string argsText = signature.substr(beginParenLoc + 1,
                                                 endParenLoc-beginParenLoc-1);
        std::vector<std::string> args = parseArguments(argsText);
        for (std::vector<std::string>::const_iterator it =
                                        args.begin(); it != args.end(); ++it) {

            // Get argument sans whitespace (bail if the arg is empty)
            std::string arg = *it;
            trimWhitespace(&arg);
            if (arg.empty()) {
                // we don't warn here because the compilation will fail anyway
                continue;
            }

            // If the argument has an = within it then it has a default value
            std::string defaultValue;
            std::string::size_type eqPos = arg.find_first_of('=');
            if ( (eqPos != std::string::npos) && ((eqPos + 1) < arg.size()) ) {
                defaultValue = arg.substr(eqPos+1);
                trimWhitespace(&defaultValue);
                arg = arg.substr(0, eqPos);
                trimWhitespace(&arg);
            }

            // Scan backwards for whitespace to determine where the type ends
            // (we go backwards because whitespace is valid inside the type
            // identifier but invalid inside the variable name). Note that if
            // there is no whitespace we'll end up taking the whole string,
            // which allows us to capture a type with no variable (but note
            // we'll ultimately fail to parse types with no variable if they
            // have embedded whitespace)
            std::string::size_type pos = arg.find_last_of(kWhitespaceChars);

            // check for name
            std::string name;
            if (pos != std::string::npos) {
                name = arg.substr(pos);
                trimWhitespace(&name);
            }
            if (name.empty()) {
                rcppExportInvalidParameterWarning(arg, lineNumber);
                return Function();
            }

            // check for type string
            Type type = parseType(arg.substr(0, pos));
            if (type.empty()) {
                rcppExportInvalidParameterWarning(arg, lineNumber);
                return Function();
            }

            // add argument
            arguments.push_back(Argument(name, type, defaultValue));
        }

        return Function(type, name, arguments, signature);
    }


    // Parse the text of a function signature from the specified line
    std::string SourceFileAttributesParser::parseSignature(size_t lineNumber) {

        // Look for the next {
        std::string signature;
        for (int i = lineNumber; i<lines_.size(); i++) {
            std::string line;
            line = lines_[i];
            std::string::size_type bracePos = line.find('{');
            if (bracePos == std::string::npos) {
                signature.append(line);
                signature.push_back(' ');
            } else {
                signature.append(line.substr(0, bracePos));
                return signature;
            }
        }

        // Not found
        return std::string();
    }


    // Parse arguments from function signature. This is tricky because commas
    // are used to delimit arguments but are also valid inside template type
    // qualifiers.
    std::vector<std::string> SourceFileAttributesParser::parseArguments(
                                                const std::string& argText) {

        int templateCount = 0;
        int parenCount = 0;
        bool insideQuotes = false;
        std::string currentArg;
        std::vector<std::string> args;
        char prevChar = 0;
        for (std::string::const_iterator
                            it = argText.begin(); it != argText.end(); ++it) {
            char ch = *it;

            if (ch == '"' && prevChar != '\\') {
                insideQuotes = !insideQuotes;
            }

            if ((ch == ',') &&
                (templateCount == 0) &&
                (parenCount == 0) &&
                !insideQuotes) {
                args.push_back(currentArg);
                currentArg.clear();
                continue;
            } else {
                currentArg.push_back(ch);
                switch(ch) {
                    case '<':
                        templateCount++;
                        break;
                    case '>':
                        templateCount--;
                        break;
                    case '(':
                        parenCount++;
                        break;
                    case ')':
                        parenCount--;
                        break;
                }
            }

            prevChar = ch;
        }

        if (!currentArg.empty())
            args.push_back(currentArg);

        return args;
    }

    Type SourceFileAttributesParser::parseType(const std::string& text) {

        const std::string constQualifier("const");
        const std::string referenceQualifier("&");

        // trim whitespace
        std::string type = text;
        trimWhitespace(&type);

        // check for const and reference
        bool isConst = false;
        bool isReference = false;
        if (type.find(constQualifier) == 0) {
            isConst = true;
            type.erase(0, constQualifier.length());
        }

        // if the type is now empty (because it was detected as only const)
        // then this is an invalid state so we bail
        if (type.empty())
            return Type();

        if (type.find(referenceQualifier) ==
            (type.length() - referenceQualifier.length())) {
            isReference = true;
            type.erase(type.length() - referenceQualifier.length());
        }
        trimWhitespace(&type);

        // if the type is now empty because of some strange parse then bail
        if (type.empty())
            return Type();

        return Type(type, isConst, isReference);
    }

    // Validation helpers

    bool SourceFileAttributesParser::isKnownAttribute(const std::string& name)
                                                                        const {
        return name == kExportAttribute ||
               name == kDependsAttribute ||
               name == kPluginsAttribute ||
               name == kInterfacesAttribute;
    }

    // Print an attribute parsing related warning
    void SourceFileAttributesParser::attributeWarning(
                                                const std::string& message,
                                                const std::string& attribute,
                                                size_t lineNumber) {

        // get basename of source file for warning message
        Rcpp::Function basename = Rcpp::Environment::base_env()["basename"];
        std::string file = Rcpp::as<std::string>(basename(sourceFile_));

        std::ostringstream ostr;
        ostr << message;
        if (!attribute.empty())
            ostr << " for " << attribute << " attribute";
        ostr << " at " << file << ":" << lineNumber;

        showWarning(ostr.str());
    }

    void SourceFileAttributesParser::attributeWarning(
                                            const std::string& message,
                                            size_t lineNumber) {
        attributeWarning(message, "", lineNumber);
    }

    void SourceFileAttributesParser::rcppExportWarning(
                                             const std::string& message,
                                             size_t lineNumber) {
        attributeWarning(message, "Rcpp::export", lineNumber);
    }

    void SourceFileAttributesParser::rcppExportNoFunctionFoundWarning(
                                                          size_t lineNumber) {
        rcppExportWarning("No function found", lineNumber);
    }

    void SourceFileAttributesParser::rcppExportInvalidParameterWarning(
                                                    const std::string& param,
                                                    size_t lineNumber) {
        rcppExportWarning("Invalid parameter: "
                          "'" + param + "'", lineNumber);
    }

    void SourceFileAttributesParser::rcppInterfacesWarning(
                                                    const std::string& message,
                                                    size_t lineNumber) {
        attributeWarning(message + " (valid interfaces are 'r' and 'cpp')",
                        "Rcpp::interfaces", lineNumber);
    }


    // Track /* */ comment state
    void CommentState::submitLine(const std::string& line) {
        std::size_t pos = 0;
        while (pos != std::string::npos) {

            // check for a // which would invalidate any other token found
            std::size_t lineCommentPos = line.find("//", pos);

            // look for the next token
            std::string token = inComment() ? "*/" : "/*";
            pos = line.find(token, pos);

            // process the comment token if found
            if (pos != std::string::npos) {

                // break if the line comment precedes the comment token
                if (lineCommentPos != std::string::npos && lineCommentPos < pos)
                    break;

                inComment_ = !inComment_;
                pos += token.size();
            }
        }
    }

} // namespace attributes
} // namespace Rcpp


/*******************************************************************
 * AttributesGen.cpp
 *******************************************************************/

namespace Rcpp {
namespace attributes {

    // constants
    namespace {
        const char * const kRcppExportsSuffix = "_RcppExports.h";
        const char * const kTrySuffix = "_try";
    }

    ExportsGenerator::ExportsGenerator(const std::string& targetFile,
                                       const std::string& package,
                                       const std::string& commentPrefix)
        : targetFile_(targetFile),
          package_(package),
          commentPrefix_(commentPrefix),
          hasCppInterface_(false) {

        // read the existing target file if it exists
        if (FileInfo(targetFile_).exists()) {
            std::ifstream ifs(targetFile_.c_str());
            if (ifs.fail())
                throw Rcpp::file_io_error(targetFile_);
            std::stringstream buffer;
            buffer << ifs.rdbuf();
            existingCode_ = buffer.str();
        }

        // see if this is safe to overwite and throw if it isn't
        if (!isSafeToOverwrite())
            throw Rcpp::file_exists(targetFile_);
    }

    void ExportsGenerator::writeFunctions(
                                const SourceFileAttributes& attributes,
                                bool verbose) {

        if (attributes.hasInterface(kInterfaceCpp))
            hasCppInterface_ = true;

        doWriteFunctions(attributes, verbose);
    }

    // Commit the stream -- is a no-op if the existing code is identical
    // to the generated code. Returns true if data was written and false
    // if it wasn't (throws exception on io error)
    bool ExportsGenerator::commit(const std::string& preamble) {

        // get the generated code
        std::string code = codeStream_.str();

        // if there is no generated code AND the exports file does not
        // currently exist then do nothing
        if (code.empty() && !FileInfo(targetFile_).exists())
            return false;

        // write header/preamble
        std::ostringstream headerStream;
        headerStream << commentPrefix_ << " This file was generated by "
                     << "Rcpp::compileAttributes" << std::endl;
        headerStream << commentPrefix_ << " Generator token: "
                     << generatorToken() << std::endl << std::endl;
        if (!preamble.empty())
            headerStream << preamble;

        // get generated code and only write it if there was a change
        std::string generatedCode = headerStream.str() + code;
        if (generatedCode != existingCode_) {
            // open the file
            std::ofstream ofs(targetFile_.c_str(),
                              std::ofstream::out | std::ofstream::trunc);
            if (ofs.fail())
                throw Rcpp::file_io_error(targetFile_);

            // write generated code and return
            ofs << generatedCode;
            ofs.close();
            return true;
        }
        else {
            return false;
        }
    }

    // Remove the generated file entirely
    bool ExportsGenerator::remove() {
        return removeFile(targetFile_);
    }

    CppExportsGenerator::CppExportsGenerator(const std::string& packageDir,
                                             const std::string& package,
                                             const std::string& fileSep)
        : ExportsGenerator(
            packageDir + fileSep + "src" +  fileSep + "RcppExports.cpp",
            package,
            "//")
    {
    }

    void CppExportsGenerator::doWriteFunctions(
                                 const SourceFileAttributes& attributes,
                                 bool verbose) {

        // generate functions
        generateCpp(ostr(),
                    attributes,
                    true,
                    attributes.hasInterface(kInterfaceCpp),
                    package());

        // track cppExports and signatures (we use these at the end to
        // generate the ValidateSignature and RegisterCCallable functions)
        if (attributes.hasInterface(kInterfaceCpp)) {
            for (SourceFileAttributes::const_iterator
                       it = attributes.begin(); it != attributes.end(); ++it) {
                if (it->isExportedFunction()) {
                    // add it to the list if it's not hidden
                    Function fun = it->function().renamedTo(it->exportedName());
                    if (!fun.isHidden())
                        cppExports_.push_back(*it);
                }
            }
        }

        // verbose if requested
        if (verbose) {
            Rcpp::Rcout << "Exports from " << attributes.sourceFile() << ":"
                        << std::endl;
            for (std::vector<Attribute>::const_iterator
                    it = attributes.begin(); it != attributes.end(); ++it) {
                if (it->isExportedFunction())
                    Rcpp::Rcout << "   " << it->function() << std::endl;
            }
            Rcpp::Rcout << std::endl;
        }
    }

    void CppExportsGenerator::writeEnd()
    {
        // generate a function that can be used to validate exported
        // functions and their signatures prior to looking up with
        // GetCppCallable (otherwise inconsistent signatures between
        // client and library would cause a crash)
        if (hasCppInterface()) {

            ostr() << std::endl;
            ostr() << "// validate"
                   << " (ensure exported C++ functions exist before "
                   << "calling them)" << std::endl;
            ostr() << "static int " << exportValidationFunctionRegisteredName()
                   << "(const char* sig) { " << std::endl;
            ostr() << "    static std::set<std::string> signatures;"
                   << std::endl;
            ostr() << "    if (signatures.empty()) {" << std::endl;

            for (std::size_t i=0;i<cppExports_.size(); i++) {
                const Attribute& attr = cppExports_[i];
                ostr() << "        signatures.insert(\""
                       << attr.function().signature(attr.exportedName())
                       << "\");" << std::endl;
            }
            ostr() << "    }" << std::endl;
            ostr() << "    return signatures.find(sig) != signatures.end();"
                   << std::endl;
            ostr() << "}" << std::endl;

            // generate a function that will register all of our C++
            // exports as C-callable from other packages
            ostr() << std::endl;
            ostr() << "// registerCCallable (register entry points for "
                      "exported C++ functions)" << std::endl;
            ostr() << "RcppExport SEXP " << registerCCallableExportedName()
                   << "() { " << std::endl;
            for (std::size_t i=0;i<cppExports_.size(); i++) {
                const Attribute& attr = cppExports_[i];
                std::string name = package() + "_" + attr.exportedName();
                ostr() << registerCCallable(
                              4,
                              attr.exportedName(),
                              attr.function().name() + kTrySuffix);
                ostr() << std::endl;
            }
            ostr() << registerCCallable(4,
                                        exportValidationFunction(),
                                        exportValidationFunction());
            ostr() << std::endl;
            ostr() << "    return R_NilValue;" << std::endl;
            ostr() << "}" << std::endl;
         }
    }

    std::string CppExportsGenerator::registerCCallable(
                                        size_t indent,
                                        const std::string& exportedName,
                                        const std::string& name) const {
        std::ostringstream ostr;
        std::string indentStr(indent, ' ');
        ostr <<  indentStr << "R_RegisterCCallable(\"" << package() << "\", "
              << "\"" << package() << "_" << exportedName << "\", "
              << "(DL_FUNC)" << package() << "_" << name << ");";
        return ostr.str();
    }

    bool CppExportsGenerator::commit(const std::vector<std::string>& includes) {

        // includes
        std::ostringstream ostr;
        if (!includes.empty()) {
            for (std::size_t i=0;i<includes.size(); i++)
                ostr << includes[i] << std::endl;
        }
        if (hasCppInterface()) {
            ostr << "#include <string>" << std::endl;
            ostr << "#include <set>" << std::endl;
        }
        ostr << std::endl;

        // always bring in Rcpp
        ostr << "using namespace Rcpp;" << std::endl << std::endl;

        // commit with preamble
        return ExportsGenerator::commit(ostr.str());
    }

    CppExportsIncludeGenerator::CppExportsIncludeGenerator(
                                            const std::string& packageDir,
                                            const std::string& package,
                                            const std::string& fileSep)
        : ExportsGenerator(
            packageDir +  fileSep + "inst" +  fileSep + "include" +
            fileSep + package + kRcppExportsSuffix,
            package,
            "//")
    {
        includeDir_ = packageDir +  fileSep + "inst" +  fileSep + "include";
    }

    void CppExportsIncludeGenerator::writeBegin() {

        ostr() << "namespace " << package() << " {"
               << std::endl << std::endl;

        // Import Rcpp into this namespace. This allows declarations to
        // be written without fully qualifying all Rcpp types. The only
        // negative side-effect is that when this package's namespace
        // is imported it will also pull in Rcpp. However since this is
        // opt-in and represents a general desire to do namespace aliasing
        // this seems okay
        ostr() << "    using namespace Rcpp;" << std::endl << std::endl;

        // Write our export validation helper function. Putting it in
        // an anonymous namespace will hide it from callers and give
        // it per-translation unit linkage
        ostr() << "    namespace {" << std::endl;
        ostr() << "        void validateSignature(const char* sig) {"
               << std::endl;
        ostr() << "            Rcpp::Function require = "
               << "Rcpp::Environment::base_env()[\"require\"];"
               << std::endl;
        ostr() << "            require(\"" << package() << "\", "
               << "Rcpp::Named(\"quietly\") = true);"
               << std::endl;

        std::string validate = "validate";
        std::string fnType = "Ptr_" + validate;
        ostr() << "            typedef int(*" << fnType << ")(const char*);"
               << std::endl;

        std::string ptrName = "p_" + validate;
        ostr() << "            static " << fnType << " " << ptrName << " = "
               << "(" << fnType << ")" << std::endl
               << "                "
               << getCCallable(exportValidationFunctionRegisteredName())
               << ";" << std::endl;
        ostr() << "            if (!" << ptrName << "(sig)) {" << std::endl;
        ostr() << "                throw Rcpp::function_not_exported("
               << std::endl
               << "                    "
               << "\"C++ function with signature '\" + std::string(sig) + \"' not found in " << package()
               << "\");" << std::endl;
        ostr() << "            }" << std::endl;
        ostr() << "        }" << std::endl;

        ostr() << "    }" << std::endl << std::endl;
    }

    void CppExportsIncludeGenerator::doWriteFunctions(
                                    const SourceFileAttributes& attributes,
                                    bool verbose) {

        // don't write anything if there is no C++ interface
        if (!attributes.hasInterface(kInterfaceCpp))
            return;

        for(std::vector<Attribute>::const_iterator
            it = attributes.begin(); it != attributes.end(); ++it) {

            if (it->isExportedFunction()) {

                Function function =
                    it->function().renamedTo(it->exportedName());

                // if it's hidden then don't generate a C++ interface
                if (function.isHidden())
                    continue;

                ostr() << "    inline " << function << " {"
                        << std::endl;

                std::string fnType = "Ptr_" + function.name();
                ostr() << "        typedef SEXP(*" << fnType << ")(";
                for (size_t i=0; i<function.arguments().size(); i++) {
                    ostr() << "SEXP";
                    if (i != (function.arguments().size()-1))
                        ostr() << ",";
                }
                ostr() << ");" << std::endl;

                std::string ptrName = "p_" + function.name();
                ostr() << "        static " << fnType << " "
                       << ptrName << " = NULL;"
                       << std::endl;
                ostr() << "        if (" << ptrName << " == NULL) {"
                       << std::endl;
                ostr() << "            validateSignature"
                       << "(\"" << function.signature() << "\");"
                       << std::endl;
                ostr() << "            " << ptrName << " = "
                       << "(" << fnType << ")"
                       << getCCallable(package() + "_" + function.name()) << ";"
                       << std::endl;
                ostr() << "        }" << std::endl;
                ostr() << "        RObject __result;" << std::endl;
                ostr() << "        {" << std::endl;
                ostr() << "            RNGScope __rngScope;" << std::endl;
                ostr() << "            __result = " << ptrName << "(";

                const std::vector<Argument>& args = function.arguments();
                for (std::size_t i = 0; i<args.size(); i++) {
                    ostr() << "Rcpp::wrap(" << args[i].name() << ")";
                    if (i != (args.size()-1))
                        ostr() << ", ";
                }

                ostr() << ");" << std::endl;
                ostr() << "        }" << std::endl;

                ostr() << "        if (__result.inherits(\"interrupted-error\"))"
                       << std::endl
                       << "            throw Rcpp::internal::InterruptedException();"
                       << std::endl;
                ostr() << "        if (__result.inherits(\"try-error\"))"
                       << std::endl
                       << "            throw Rcpp::exception(as<std::string>("
                       << "__result).c_str());"
                       << std::endl;
                ostr() << "        return Rcpp::as<" << function.type() << " >"
                       << "(__result);" << std::endl;

                ostr() << "    }" << std::endl << std::endl;
            }
        }
    }

    void CppExportsIncludeGenerator::writeEnd() {
        ostr() << "}" << std::endl;
        ostr() << std::endl;
        ostr() << "#endif // " << getHeaderGuard() << std::endl;
    }

    bool CppExportsIncludeGenerator::commit(
                                    const std::vector<std::string>& includes) {

        if (hasCppInterface()) {

            // create the include dir if necessary
            createDirectory(includeDir_);

            // generate preamble
            std::ostringstream ostr;

            // header guard
            std::string guard = getHeaderGuard();
            ostr << "#ifndef " << guard << std::endl;
            ostr << "#define " << guard << std::endl << std::endl;

            // includes
            if (!includes.empty()) {
                for (std::size_t i=0;i<includes.size(); i++)
                {
                    // don't do inst/include here
                    if (includes[i].find("#include \"../inst/include/")
                                                       == std::string::npos)
                    {
                        ostr << includes[i] << std::endl;
                    }
                }
                ostr << std::endl;
            }

            // commit with preamble
            return ExportsGenerator::commit(ostr.str());
        }
        else {
            return ExportsGenerator::remove();
        }
    }

    std::string CppExportsIncludeGenerator::getCCallable(
                                        const std::string& function) const {
        std::ostringstream ostr;
        ostr << "R_GetCCallable"
             << "(\"" << package() << "\", "
             << "\"" << function << "\")";
        return ostr.str();
    }

    std::string CppExportsIncludeGenerator::getHeaderGuard() const {
        return "__" + package() + "_RcppExports_h__";
    }

    CppPackageIncludeGenerator::CppPackageIncludeGenerator(
                                            const std::string& packageDir,
                                            const std::string& package,
                                            const std::string& fileSep)
        : ExportsGenerator(
            packageDir +  fileSep + "inst" +  fileSep + "include" +
            fileSep + package + ".h",
            package,
            "//")
    {
        includeDir_ = packageDir +  fileSep + "inst" +  fileSep + "include";
    }

    void CppPackageIncludeGenerator::writeEnd() {
        if (hasCppInterface()) {
            // header guard
            std::string guard = getHeaderGuard();
            ostr() << "#ifndef " << guard << std::endl;
            ostr() << "#define " << guard << std::endl << std::endl;

            ostr() << "#include \"" << package() << kRcppExportsSuffix
                   << "\"" << std::endl;

            ostr() << std::endl;
            ostr() << "#endif // " << getHeaderGuard() << std::endl;
        }
    }

    bool CppPackageIncludeGenerator::commit(
                                const std::vector<std::string>& includes) {

        if (hasCppInterface()) {

            // create the include dir if necessary
            createDirectory(includeDir_);

            // commit
            return ExportsGenerator::commit();
        }
        else {
            return ExportsGenerator::remove();
        }
    }

    std::string CppPackageIncludeGenerator::getHeaderGuard() const {
        return "__" + package() + "_h__";
    }

    RExportsGenerator::RExportsGenerator(const std::string& packageDir,
                                         const std::string& package,
                                         const std::string& fileSep)
        : ExportsGenerator(
            packageDir + fileSep + "R" +  fileSep + "RcppExports.R",
            package,
            "#")
    {
    }

    void RExportsGenerator::doWriteFunctions(
                                        const SourceFileAttributes& attributes,
                                        bool verbose) {

        // write standalone roxygen chunks
        const std::vector<std::vector<std::string> >& roxygenChunks =
                                                    attributes.roxygenChunks();
        for (std::size_t i = 0; i<roxygenChunks.size(); i++) {
            const std::vector<std::string>& chunk = roxygenChunks[i];
            for (std::size_t l = 0; l < chunk.size(); l++)
                ostr() << chunk[l] << std::endl;
            ostr() << "NULL" << std::endl << std::endl;
        }

        // write exported functions
        if (attributes.hasInterface(kInterfaceR)) {
            // process each attribute
            for(std::vector<Attribute>::const_iterator
                it = attributes.begin(); it != attributes.end(); ++it) {

                // alias the attribute and function (bail if not export)
                const Attribute& attribute = *it;
                if (!attribute.isExportedFunction())
                    continue;
                const Function& function = attribute.function();

                // print roxygen lines
                for (size_t i=0; i<attribute.roxygen().size(); i++)
                    ostr() << attribute.roxygen()[i] << std::endl;

                // build the parameter list
                std::string args = generateRArgList(function);

                // determine the function name
                std::string name = attribute.exportedName();

                // write the function
                ostr() << name << " <- function(" << args << ") {"
                       << std::endl;
                ostr() << "    ";
                if (function.type().isVoid())
                    ostr() << "invisible(";
                ostr() << ".Call(";
                ostr() << "'" << package() << "_" << function.name() << "', "
                       << "PACKAGE = '" << package() << "'";

                // add arguments
                const std::vector<Argument>& arguments = function.arguments();
                for (size_t i = 0; i<arguments.size(); i++)
                    ostr() << ", " << arguments[i].name();
                ostr() << ")";
                if (function.type().isVoid())
                    ostr() << ")";
                ostr() << std::endl;

                ostr() << "}" << std::endl << std::endl;
            }
        }
    }

    void RExportsGenerator::writeEnd() {
        if (hasCppInterface()) {
             // register all C-callable functions
            ostr() << "# Register entry points for exported C++ functions"
                   << std::endl;
            ostr() << "methods::setLoadAction(function(ns) {" << std::endl;
            ostr() << "    .Call('" << registerCCallableExportedName()
                   << "', PACKAGE = '" << package() << "')"
                   << std::endl << "})" << std::endl;
        }
    }

    bool RExportsGenerator::commit(const std::vector<std::string>& includes) {
        return ExportsGenerator::commit();
    }

    ExportsGenerators::~ExportsGenerators() {
        try {
            for(Itr it = generators_.begin(); it != generators_.end(); ++it)
                delete *it;
            generators_.clear();
        }
        catch(...) {}
    }

    void ExportsGenerators::add(ExportsGenerator* pGenerator) {
        generators_.push_back(pGenerator);
    }

    void ExportsGenerators::writeBegin() {
        for(Itr it = generators_.begin(); it != generators_.end(); ++it)
            (*it)->writeBegin();
    }

    void ExportsGenerators::writeFunctions(
                                const SourceFileAttributes& attributes,
                                bool verbose) {
        for(Itr it = generators_.begin(); it != generators_.end(); ++it)
            (*it)->writeFunctions(attributes, verbose);
    }

    void ExportsGenerators::writeEnd() {
        for(Itr it = generators_.begin(); it != generators_.end(); ++it)
            (*it)->writeEnd();
    }

    // Commit and return a list of the files that were updated
    std::vector<std::string> ExportsGenerators::commit(
                            const std::vector<std::string>& includes) {

        std::vector<std::string> updated;

        for(Itr it = generators_.begin(); it != generators_.end(); ++it) {
            if ((*it)->commit(includes))
                updated.push_back((*it)->targetFile());
        }

        return updated;
    }

    // Remove and return a list of files that were removed
    std::vector<std::string> ExportsGenerators::remove() {
        std::vector<std::string> removed;
        for(Itr it = generators_.begin(); it != generators_.end(); ++it) {
            if ((*it)->remove())
                removed.push_back((*it)->targetFile());
        }
        return removed;
    }


    // Helpers for converting C++  default arguments to R default arguments
    namespace {

        // convert a C++ numeric argument to an R argument value
        // (returns empty string if no conversion is possible)
        std::string cppNumericArgToRArg(const std::string& type,
                                        const std::string& cppArg) {
            // check for a number
            double num;
            std::stringstream argStream(cppArg);
            if ((argStream >> num)) {

                // L suffix means return the value literally
                if (!argStream.eof()) {
                    std::string suffix;
                    argStream >> suffix;
                    if (argStream.eof() && suffix == "L")
                        return cppArg;
                }

                // no decimal and the type isn't explicitly double or
                // float means integer
                if (cppArg.find('.') == std::string::npos &&
                    type != "double" && type != "float")
                    return cppArg + "L";

                // otherwise return arg literally
                else
                    return cppArg;
            }
            else {
                return std::string();
            }
        }

        // convert a C++ ::create style argument value to an R argument
        // value (returns empty string if no conversion is possible)
        std::string cppCreateArgToRArg(const std::string& cppArg) {

            std::string create = "::create";
            size_t createLoc = cppArg.find(create);
            if (createLoc == std::string::npos ||
                ((createLoc + create.length()) >= cppArg.size())) {
                return std::string();
            }

            std::string type = cppArg.substr(0, createLoc);
            std::string rcppScope = "Rcpp::";
            size_t rcppLoc = type.find(rcppScope);
            if (rcppLoc == 0 && type.size() > rcppScope.length())
                type = type.substr(rcppScope.length());

            std::string args = cppArg.substr(createLoc + create.length());
            if (type == "CharacterVector")
                return "as.character( c" + args + ")";
            if (type == "IntegerVector")
                return "as.integer( c" + args + ")";
            if (type == "NumericVector")
                return "as.numeric( c" + args + ")";
            if (type == "LogicalVector")
                return "as.logical( c" + args + ")";

            return std::string();
        }

        // convert a C++ Matrix to an R argument (returns empty string
        // if no conversion possible)
        std::string cppMatrixArgToRArg(const std::string& cppArg) {

            // look for Matrix
            std::string matrix = "Matrix";
            size_t matrixLoc = cppArg.find(matrix);
            if (matrixLoc == std::string::npos ||
                ((matrixLoc + matrix.length()) >= cppArg.size())) {
                return std::string();
            }

            std::string args = cppArg.substr(matrixLoc + matrix.length());
            return "matrix" + args;
        }

        // convert a C++ literal to an R argument (returns empty string
        // if no conversion possible)
        std::string cppLiteralArgToRArg(const std::string& cppArg) {
            if (cppArg == "true")
                return "TRUE";
            else if (cppArg == "false")
                return "FALSE";
            else if (cppArg == "R_NilValue")
                return "NULL";
            else if (cppArg == "NA_STRING")
                return "NA_character_";
            else if (cppArg == "NA_INTEGER")
                return "NA_integer_";
            else if (cppArg == "NA_LOGICAL")
                return "NA_integer_";
            else if (cppArg == "NA_REAL")
                return "NA_real_";
            else
                return std::string();
        }

        // convert an Rcpp container constructor to an R argument
        // (returns empty string if no conversion possible)
        std::string cppConstructorArgToRArg(const std::string& cppArg) {

            // map Rcpp containers to R default initializers
            static std::map<std::string, std::string> RcppContainerToR;
            RcppContainerToR.insert(std::make_pair("NumericVector", "numeric"));
            RcppContainerToR.insert(std::make_pair("DoubleVector", "numeric"));
            RcppContainerToR.insert(std::make_pair("CharacterVector", "character"));
            RcppContainerToR.insert(std::make_pair("IntegerVector", "integer"));
            RcppContainerToR.insert(std::make_pair("LogicalVector", "logical"));
            RcppContainerToR.insert(std::make_pair("ComplexVector", "complex"));

            // for each entry in the map above, see if we find it; if we do,
            // return the R version
            typedef std::map<std::string, std::string>::const_iterator Iterator;
            for (Iterator it = RcppContainerToR.begin(); it != RcppContainerToR.end(); ++it) {
                size_t loc = cppArg.find(it->first);
                if (loc != std::string::npos) {
                    return it->second + cppArg.substr(it->first.size(), std::string::npos);
                }
            }

            return std::string();

        }

        // convert a C++ argument value to an R argument value (returns empty
        // string if no conversion is possible)
        std::string cppArgToRArg(const std::string& type,
                                 const std::string& cppArg) {

            // try for quoted string
            if (isQuoted(cppArg))
                return cppArg;

            // try for literal
            std::string rArg = cppLiteralArgToRArg(cppArg);
            if (!rArg.empty())
                return rArg;

            // try for a create arg
            rArg = cppCreateArgToRArg(cppArg);
            if (!rArg.empty())
                return rArg;

            // try for a matrix arg
            rArg = cppMatrixArgToRArg(cppArg);
            if (!rArg.empty())
                return rArg;

            // try for a numeric arg
            rArg = cppNumericArgToRArg(type, cppArg);
            if (!rArg.empty())
                return rArg;

            // try for a constructor arg
            rArg = cppConstructorArgToRArg(cppArg);
            if (!rArg.empty())
                return rArg;

            // couldn't parse the arg
            return std::string();
        }

    } // anonymous namespace

    // Generate an R argument list for a function
    std::string generateRArgList(const Function& function) {
        std::ostringstream argsOstr;
        const std::vector<Argument>& arguments = function.arguments();
        for (size_t i = 0; i<arguments.size(); i++) {
            const Argument& argument = arguments[i];
            argsOstr << argument.name();
            if (!argument.defaultValue().empty()) {
                std::string rArg = cppArgToRArg(argument.type().name(),
                                                argument.defaultValue());
                if (!rArg.empty()) {
                    argsOstr << " = " << rArg;
                } else {
                    showWarning("Unable to parse C++ default value '" +
                                argument.defaultValue() + "' for argument "+
                                argument.name() + " of function " +
                                function.name());
                }
            }

            if (i != (arguments.size()-1))
                argsOstr << ", ";
        }
        return argsOstr.str();
    }

    // Generate the C++ code required to make [[Rcpp::export]] functions
    // available as C symbols with SEXP parameters and return
    void generateCpp(std::ostream& ostr,
                     const SourceFileAttributes& attributes,
                     bool includePrototype,
                     bool cppInterface,
                     const std::string& contextId) {

        // process each attribute
        for(std::vector<Attribute>::const_iterator
            it = attributes.begin(); it != attributes.end(); ++it) {

            // alias the attribute and function (bail if not export)
            const Attribute& attribute = *it;
            if (!attribute.isExportedFunction())
                continue;
            const Function& function = attribute.function();

            // include prototype if requested
            if (includePrototype) {
                ostr << "// " << function.name() << std::endl;
                ostr << function << ";";
            }

            // write the C++ callable SEXP-based function (this version
            // returns errors via "try-error")
            ostr << std::endl;
            ostr << (cppInterface ? "static" : "RcppExport");
            ostr << " SEXP ";
            std::string funcName = contextId + "_" + function.name();
            ostr << funcName;
            if (cppInterface)
                ostr << kTrySuffix;
            ostr << "(";
            std::ostringstream ostrArgs;
            const std::vector<Argument>& arguments = function.arguments();
            for (size_t i = 0; i<arguments.size(); i++) {
                const Argument& argument = arguments[i];
                ostrArgs << "SEXP " << argument.name() << "SEXP";
                if (i != (arguments.size()-1))
                    ostrArgs << ", ";
            }
            std::string args = ostrArgs.str();
            ostr << args << ") {" << std::endl;
            ostr << "BEGIN_RCPP" << std::endl;
            if (!function.type().isVoid())
                ostr << "    SEXP __sexp_result;" << std::endl;
            ostr << "    {" << std::endl;
            if (!cppInterface)
                ostr << "        Rcpp::RNGScope __rngScope;" << std::endl;
            for (size_t i = 0; i<arguments.size(); i++) {
                const Argument& argument = arguments[i];

                ostr << "        Rcpp::traits::input_parameter< "
                     << argument.type().full_name() << " >::type " << argument.name()
                     << "(" << argument.name() << "SEXP );" << std::endl;
            }

            ostr << "        ";
            if (!function.type().isVoid())
                ostr << function.type() << " __result = ";
            ostr << function.name() << "(";
            for (size_t i = 0; i<arguments.size(); i++) {
                const Argument& argument = arguments[i];
                ostr << argument.name();
                if (i != (arguments.size()-1))
                    ostr << ", ";
            }
            ostr << ");" << std::endl;

            if (!function.type().isVoid())
            {
                ostr << "        PROTECT(__sexp_result = Rcpp::wrap(__result));"
                     << std::endl;
            }
            ostr << "    }" << std::endl;
            if (!function.type().isVoid())
            {
                ostr << "    UNPROTECT(1);" << std::endl;
                ostr << "    return __sexp_result;" << std::endl;
            }
            else
            {
                ostr << "    return R_NilValue;" << std::endl;
            }
            ostr << (cppInterface ? "END_RCPP_RETURN_ERROR" : "END_RCPP")
                 << std::endl;
            ostr << "}" << std::endl;

            // Now write an R wrapper that returns error via Rf_error
            if (cppInterface) {
                ostr << "RcppExport SEXP " << funcName << "(" << args << ") {"
                     << std::endl;
                ostr << "    SEXP __result;" << std::endl;
                ostr << "    {" << std::endl;
                ostr << "        Rcpp::RNGScope __rngScope;" << std::endl;
                ostr << "        __result = PROTECT(" << funcName
                     << kTrySuffix << "(";
                for (size_t i = 0; i<arguments.size(); i++) {
                    const Argument& argument = arguments[i];
                    ostr << argument.name() << "SEXP";
                    if (i != (arguments.size()-1))
                        ostr << ", ";
                }
                ostr << "));" << std::endl;
                ostr << "    }" << std::endl;
                ostr << "    Rboolean __isInterrupt = Rf_inherits(__result, \"interrupted-error\");"
                     << std::endl
                     << "    if (__isInterrupt) {" << std::endl
                     << "        UNPROTECT(1);" << std::endl
                     << "        Rf_onintr();" << std::endl
                     << "    }" << std::endl
                     << "    Rboolean __isError = Rf_inherits(__result, \"try-error\");"
                     << std::endl
                     << "    if (__isError) {" << std::endl
                     << "        SEXP __msgSEXP = Rf_asChar(__result);" << std::endl
                     << "        UNPROTECT(1);" << std::endl
                     << "        Rf_error(CHAR(__msgSEXP));" << std::endl
                     << "    }" << std::endl
                     << "    UNPROTECT(1);" << std::endl
                     << "    return __result;" << std::endl
                     << "}" << std::endl;
            }
        }
    }

} // namespace attributes
} // namespace Rcpp





// provide implementations for util
namespace Rcpp {
namespace attributes {

    // Utility class for getting file existence and last modified time
    FileInfo::FileInfo(const std::string& path)
        : path_(path), exists_(false), lastModified_(0)
    {
    #ifdef _WIN32
        struct _stat buffer;
        int result = _stat(path.c_str(), &buffer);
    #else
        struct stat buffer;
        int result = stat(path.c_str(), &buffer);
    #endif
        if (result != 0) {
            if (errno == ENOENT)
                exists_ = false;
            else
                throw Rcpp::file_io_error(errno, path);
        } else {
            exists_ = true;
            lastModified_ = buffer.st_mtime;
        }
    }

    // Remove a file (call back into R for this)
    bool removeFile(const std::string& path) {
        if (FileInfo(path).exists()) {
            Rcpp::Function rm = Rcpp::Environment::base_env()["file.remove"];
            rm(path);
            return true;
        }
        else {
            return false;
        }
    }

    // Recursively create a directory (call back into R for this)
    void createDirectory(const std::string& path) {
        if (!FileInfo(path).exists()) {
            Rcpp::Function mkdir = Rcpp::Environment::base_env()["dir.create"];
            mkdir(path, Rcpp::Named("recursive") = true);
        }
    }

     // Known whitespace chars
    const char * const kWhitespaceChars = " \f\n\r\t\v";

    // Query whether a character is whitespace
    bool isWhitespace(char ch) {
        return std::strchr(kWhitespaceChars, ch) != NULL;
    }

    // Remove trailing line comments -- ie, find comments that don't begin
    // a line, and remove them. We avoid stripping attributes.
    void stripTrailingLineComments(std::string* pStr) {

        if (pStr->empty()) return;

        size_t len = pStr->length();
        bool inString = false;
        size_t idx = 0;

        // if this is an roxygen comment, then bail
        if (isRoxygenCpp(*pStr)) return;

        // skip over initial whitespace
        idx = pStr->find_first_not_of(kWhitespaceChars);
        if (idx == std::string::npos) return;

        // skip over a first comment
        if (idx + 1 < len && pStr->at(idx) == '/' && pStr->at(idx + 1) == '/') {
            idx = idx + 2;
        }

        // since we are searching for "//", we iterate up to 2nd last character
        while (idx < len - 1) {

            if (inString) {
                if (pStr->at(idx) == '"' && pStr->at(idx - 1) != '\\') {
                    inString = false;
                }
            } else {
                if (pStr->at(idx) == '"') {
                    inString = true;
                }
            }

            if (!inString &&
                pStr->at(idx) == '/' &&
                pStr->at(idx + 1) == '/') {
                pStr->erase(idx);
                return;
            }
            ++idx;
        }
    }

    // Trim a string
    void trimWhitespace(std::string* pStr) {

        // skip empty case
        if (pStr->empty())
            return;

        // trim right
        std::string::size_type pos = pStr->find_last_not_of(kWhitespaceChars);
        if (pos != std::string::npos)
            pStr->erase(pos + 1);

        // trim left
        pos = pStr->find_first_not_of(kWhitespaceChars);
        pStr->erase(0, pos);
    }

    // Strip balanced quotes from around a string (assumes already trimmed)
    void stripQuotes(std::string* pStr) {
        if (pStr->length() < 2)
            return;
        char quote = *(pStr->begin());
        if ( (quote == '\'' || quote == '\"') && (*(pStr->rbegin()) == quote) )
            *pStr = pStr->substr(1, pStr->length()-2);
    }

    // is the passed string quoted?
    bool isQuoted(const std::string& str) {
        if (str.length() < 2)
            return false;
        char quote = *(str.begin());
        return (quote == '\'' || quote == '\"') && (*(str.rbegin()) == quote);
    }

    // show a warning message
    void showWarning(const std::string& msg) {
        Rcpp::Function warning = Rcpp::Environment::base_env()["warning"];
        warning(msg, Rcpp::Named("call.") = false);
    }

    bool isRoxygenCpp(const std::string& str) {
        size_t len = str.length();
        if (len < 3) return false;
        size_t idx = str.find_first_not_of(kWhitespaceChars);
        if (idx == std::string::npos) return false;

        // make sure there are characters to check
        if (len - 2 < idx) return false;

        if (str[idx] == '/' &&
            str[idx + 1] == '/' &&
            str[idx + 2] == '\'') {
            return true;
        }

        return false;

    }

} // namespace attributes
} // namespace Rcpp


/*******************************************************************
 * Attributes.cpp
 *******************************************************************/

using namespace Rcpp::attributes;

// Implementation helpers for sourceCppContext
namespace {

    // Class that manages generation of source code for the sourceCpp dynlib
    class SourceCppDynlib {
    public:
        SourceCppDynlib() {}

        SourceCppDynlib(const std::string& cppSourcePath, Rcpp::List platform)
            :  cppSourcePath_(cppSourcePath)

        {
            // get cpp source file info
            FileInfo cppSourceFilenameInfo(cppSourcePath_);
            if (!cppSourceFilenameInfo.exists())
                throw Rcpp::file_not_found(cppSourcePath_);

            // record the base name of the source file
            Rcpp::Function basename = Rcpp::Environment::base_env()["basename"];
            cppSourceFilename_ = Rcpp::as<std::string>(basename(cppSourcePath_));

            // get platform info
            fileSep_ = Rcpp::as<std::string>(platform["file.sep"]);
            dynlibExt_ = Rcpp::as<std::string>(platform["dynlib.ext"]);

            // generate temp directory
            Rcpp::Function tempfile = Rcpp::Environment::base_env()["tempfile"];
            buildDirectory_ = Rcpp::as<std::string>(tempfile("sourcecpp_"));
            std::replace(buildDirectory_.begin(), buildDirectory_.end(), '\\', '/');
            Rcpp::Function dircreate = Rcpp::Environment::base_env()["dir.create"];
            dircreate(buildDirectory_);

            // generate a random context id
            contextId_ = "sourceCpp_" + createRandomizer();

            // regenerate the source code
            regenerateSource();
        }

        bool isEmpty() const { return cppSourcePath_.empty(); }

        bool isBuilt() const { return FileInfo(dynlibPath()).exists(); };

        bool isSourceDirty() const {
            // source file out of date means we're dirty
            if (FileInfo(cppSourcePath_).lastModified() >
                FileInfo(generatedCppSourcePath()).lastModified())
                return true;

            // no dynlib means we're dirty
            if (!FileInfo(dynlibPath()).exists())
                return true;

            // not dirty
            return false;
        }

        void regenerateSource() {

            // create new dynlib filename
            previousDynlibFilename_ = dynlibFilename_;
            dynlibFilename_ = "sourceCpp_" + createRandomizer() + dynlibExt_;

            // copy the source file to the build dir
            Rcpp::Function filecopy = Rcpp::Environment::base_env()["file.copy"];
            filecopy(cppSourcePath_, generatedCppSourcePath(), true);

            // parse attributes
            SourceFileAttributesParser sourceAttributes(cppSourcePath_);

            // generate cpp for attributes and append them
            std::ostringstream ostr;
            // always include Rcpp.h in case the user didn't
            ostr << std::endl << std::endl;
            ostr << "#include <Rcpp.h>" << std::endl;
            generateCpp(ostr, sourceAttributes, false, false, contextId_);
            generatedCpp_ = ostr.str();
            std::ofstream cppOfs(generatedCppSourcePath().c_str(),
                                 std::ofstream::out | std::ofstream::app);
            if (cppOfs.fail())
                throw Rcpp::file_io_error(generatedCppSourcePath());
            cppOfs << generatedCpp_;
            cppOfs.close();

            // generate R for attributes and write it into the build directory
            std::ofstream rOfs(generatedRSourcePath().c_str(),
                               std::ofstream::out | std::ofstream::trunc);
            if (rOfs.fail())
                throw Rcpp::file_io_error(generatedRSourcePath());

            // DLLInfo - hide using . and ensure uniqueness using contextId
            std::string dllInfo = "`." + contextId_ + "_DLLInfo`";
            rOfs << dllInfo << " <- dyn.load('" << dynlibPath() << "')"
                 << std::endl << std::endl;

            // Generate R functions
            generateR(rOfs, sourceAttributes, dllInfo);

            // remove the DLLInfo
            rOfs << std::endl << "rm(" << dllInfo << ")"
                 << std::endl;

            rOfs.close();

            // discover exported functions and dependencies
            exportedFunctions_.clear();
            depends_.clear();
            plugins_.clear();
            for (SourceFileAttributesParser::const_iterator
              it = sourceAttributes.begin(); it != sourceAttributes.end(); ++it) {

                 if (it->name() == kExportAttribute && !it->function().empty())
                    exportedFunctions_.push_back(it->exportedName());

                 else if (it->name() == kDependsAttribute) {
                     for (size_t i = 0; i<it->params().size(); ++i)
                        depends_.push_back(it->params()[i].name());
                 }

                 else if (it->name() == kPluginsAttribute) {
                     for (size_t i = 0; i<it->params().size(); ++i)
                        plugins_.push_back(it->params()[i].name());
                 }
            }

            // capture modules
            modules_ = sourceAttributes.modules();

            // capture embededded R
            embeddedR_ = sourceAttributes.embeddedR();
        }

        const std::string& contextId() const {
            return contextId_;
        }

        const std::string& cppSourcePath() const {
            return cppSourcePath_;
        }

        std::string buildDirectory() const {
            return buildDirectory_;
        }

        std::string generatedCpp() const {
            return generatedCpp_;
        }

        std::string cppSourceFilename() const {
            return cppSourceFilename_;
        }

        std::string rSourceFilename() const {
            return cppSourceFilename() + ".R";
        }

        std::string dynlibFilename() const {
            return dynlibFilename_;
        }

        std::string dynlibPath() const {
            return buildDirectory_ + fileSep_ + dynlibFilename();
        }

        std::string previousDynlibPath() const {
            if (!previousDynlibFilename_.empty())
                return buildDirectory_ + fileSep_ + previousDynlibFilename_;
            else
                return std::string();
        }

        const std::vector<std::string>& exportedFunctions() const {
            return exportedFunctions_;
        }

        const std::vector<std::string>& modules() const {
            return modules_;
        }

        const std::vector<std::string>& depends() const { return depends_; };

        const std::vector<std::string>& plugins() const { return plugins_; };

        const std::vector<std::string>& embeddedR() const { return embeddedR_; }

    private:

        std::string generatedCppSourcePath() const {
           return buildDirectory_ + fileSep_ + cppSourceFilename();
        }

         std::string generatedRSourcePath() const {
           return buildDirectory_ + fileSep_ + rSourceFilename();
        }

        void generateR(std::ostream& ostr,
                       const SourceFileAttributes& attributes,
                       const std::string& dllInfo) const
        {
            // process each attribute
            for(std::vector<Attribute>::const_iterator
                it = attributes.begin(); it != attributes.end(); ++it) {

                // alias the attribute and function (bail if not export)
                const Attribute& attribute = *it;
                if (!attribute.isExportedFunction())
                    continue;
                const Function& function = attribute.function();

                // export the function
                ostr <<  attribute.exportedName()
                     << " <- Rcpp:::sourceCppFunction("
                     << "function(" << generateRArgList(function) << ") {}, "
                     << (function.type().isVoid() ? "TRUE" : "FALSE") << ", "
                     << dllInfo << ", "
                     << "'" << contextId_ + "_" + function.name()
                     << "')" << std::endl;
            }

            // modules
            std::vector<std::string> modules = attributes.modules();
            if (modules.size() > 0)
            {
                // modules require definition of C++Object to be loaded
                ostr << "library(Rcpp)" << std::endl;

                // load each module
                for (std::vector<std::string>::const_iterator
                    it = modules.begin(); it != modules.end(); ++it)
                {
                    ostr << " populate( Rcpp::Module(\"" << *it << "\","
                         << dllInfo << "), environment() ) " << std::endl;
                }
            }

        }

        std::string createRandomizer() {
            Rcpp::Function sample = Rcpp::Environment::base_env()["sample"];
            std::ostringstream ostr;
            ostr << Rcpp::as<int>(sample(100000, 1));
            return ostr.str();
        }

    private:
        std::string cppSourcePath_;
        std::string generatedCpp_;
        std::string cppSourceFilename_;
        std::string contextId_;
        std::string buildDirectory_;
        std::string fileSep_;
        std::string dynlibFilename_;
        std::string previousDynlibFilename_;
        std::string dynlibExt_;
        std::vector<std::string> exportedFunctions_;
        std::vector<std::string> modules_;
        std::vector<std::string> depends_;
        std::vector<std::string> plugins_;
        std::vector<std::string> embeddedR_;
    };

    // Dynlib cache that allows lookup by either file path or code contents
    class SourceCppDynlibCache {

    public:
        SourceCppDynlibCache() {}

    private:
        // prohibit copying
        SourceCppDynlibCache(const SourceCppDynlibCache&);
        SourceCppDynlibCache& operator=(const SourceCppDynlibCache&);

    public:
        // Insert into cache by file name
        SourceCppDynlib* insertFile(const std::string& file,
                                    const SourceCppDynlib& dynlib) {
            Entry entry;
            entry.file = file;
            entry.dynlib = dynlib;
            entries_.push_back(entry);
            return &(entries_.rbegin()->dynlib);
        }

        // Insert into cache by code
        SourceCppDynlib* insertCode(const std::string& code,
                                    const SourceCppDynlib& dynlib) {
            Entry entry;
            entry.code = code;
            entry.dynlib = dynlib;
            entries_.push_back(entry);
            return &(entries_.rbegin()->dynlib);
        }

        // Lookup by file
        SourceCppDynlib* lookupByFile(const std::string& file) {
            for (std::size_t i = 0; i < entries_.size(); i++) {
                if (entries_[i].file == file)
                    return &(entries_[i].dynlib);
            }

            return NULL;
        }

        // Lookup by code
        SourceCppDynlib* lookupByCode(const std::string& code) {
            for (std::size_t i = 0; i < entries_.size(); i++) {
                if (entries_[i].code == code)
                    return &(entries_[i].dynlib);
            }

            return NULL;
        }

    private:
        struct Entry {
            std::string file;
            std::string code;
            SourceCppDynlib dynlib;
        };
        std::vector<Entry> entries_;
    };

} // anonymous namespace

// Create temporary build directory, generate code as necessary, and return
// the context required for the sourceCpp function to complete it's work
RcppExport SEXP sourceCppContext(SEXP sFile, SEXP sCode,
                                 SEXP sRebuild, SEXP sPlatform) {
BEGIN_RCPP
    // parameters
    std::string file = Rcpp::as<std::string>(sFile);
    std::string code = sCode != R_NilValue ? Rcpp::as<std::string>(sCode) : "";
    bool rebuild = Rcpp::as<bool>(sRebuild);
    Rcpp::List platform = Rcpp::as<Rcpp::List>(sPlatform);

    // get dynlib (using cache if possible)
    static SourceCppDynlibCache s_dynlibCache;
    SourceCppDynlib* pDynlib = !code.empty() ? s_dynlibCache.lookupByCode(code)
                                             : s_dynlibCache.lookupByFile(file);

    // check dynlib build state
    bool buildRequired = false;

    // if there is no dynlib in the cache then create one
    if (pDynlib == NULL) {
        buildRequired = true;
        SourceCppDynlib newDynlib(file, platform);
        if (!code.empty())
            pDynlib = s_dynlibCache.insertCode(code, newDynlib);
        else
            pDynlib = s_dynlibCache.insertFile(file, newDynlib);
    }

    // if the cached dynlib is dirty then regenerate the source
    else if (rebuild || pDynlib->isSourceDirty()) {
        buildRequired = true;
        pDynlib->regenerateSource();
    }

    // if the dynlib hasn't yet been built then note that
    else if (!pDynlib->isBuilt()) {
        buildRequired = true;
    }

    // return context as a list
    using namespace Rcpp;
    return List::create(
        _["contextId"] = pDynlib->contextId(),
        _["cppSourcePath"] = pDynlib->cppSourcePath(),
        _["buildRequired"] = buildRequired,
        _["buildDirectory"] = pDynlib->buildDirectory(),
        _["generatedCpp"] = pDynlib->generatedCpp(),
        _["exportedFunctions"] = pDynlib->exportedFunctions(),
        _["modules"] = pDynlib->modules(),
        _["cppSourceFilename"] = pDynlib->cppSourceFilename(),
        _["rSourceFilename"] = pDynlib->rSourceFilename(),
        _["dynlibFilename"] = pDynlib->dynlibFilename(),
        _["dynlibPath"] = pDynlib->dynlibPath(),
        _["previousDynlibPath"] = pDynlib->previousDynlibPath(),
        _["depends"] = pDynlib->depends(),
        _["plugins"] = pDynlib->plugins(),
        _["embeddedR"] = pDynlib->embeddedR());
END_RCPP
}

// Compile the attributes within the specified package directory into
// RcppExports.cpp and RcppExports.R
RcppExport SEXP compileAttributes(SEXP sPackageDir,
                                  SEXP sPackageName,
                                  SEXP sDepends,
                                  SEXP sCppFiles,
                                  SEXP sCppFileBasenames,
                                  SEXP sIncludes,
                                  SEXP sVerbose,
                                  SEXP sPlatform) {
BEGIN_RCPP
    // arguments
    std::string packageDir = Rcpp::as<std::string>(sPackageDir);
    std::string packageName = Rcpp::as<std::string>(sPackageName);

    Rcpp::CharacterVector vDepends = Rcpp::as<Rcpp::CharacterVector>(sDepends);
    std::set<std::string> depends;
    for (Rcpp::CharacterVector::iterator
                        it = vDepends.begin(); it != vDepends.end(); ++it) {
        depends.insert(std::string(*it));
    }

    std::vector<std::string> cppFiles =
                    Rcpp::as<std::vector<std::string> >(sCppFiles);
    std::vector<std::string> cppFileBasenames =
                    Rcpp::as<std::vector<std::string> >(sCppFileBasenames);
    std::vector<std::string> includes =
                    Rcpp::as<std::vector<std::string> >(sIncludes);
    bool verbose = Rcpp::as<bool>(sVerbose);
    Rcpp::List platform = Rcpp::as<Rcpp::List>(sPlatform);
    std::string fileSep = Rcpp::as<std::string>(platform["file.sep"]);

    // initialize generators
    ExportsGenerators generators;
    generators.add(new CppExportsGenerator(packageDir, packageName, fileSep));
    generators.add(new RExportsGenerator(packageDir, packageName, fileSep));

    // catch file exists exception if the include file already exists
    // and we are unable to overwrite it
    try {
        generators.add(new CppExportsIncludeGenerator(packageDir,
                                                      packageName,
                                                      fileSep));
    }
    catch(const Rcpp::file_exists& e) {
        std::string msg =
            "The header file '" + e.filePath() + "' already exists so "
            "cannot be overwritten by Rcpp::interfaces";
        throw Rcpp::exception(msg.c_str(), __FILE__, __LINE__);
    }

    // catch file exists exception for package include (because if it
    // already exists we simply leave it alone)
    try {
        generators.add(new CppPackageIncludeGenerator(packageDir,
                                                      packageName,
                                                      fileSep));
    }
    catch(const Rcpp::file_exists& e) {}

    // write begin
    generators.writeBegin();

    // Parse attributes from each file and generate code as required.
    bool haveAttributes = false;
    std::set<std::string> dependsAttribs;
    for (std::size_t i=0; i<cppFiles.size(); i++) {

        // parse file (continue if there is no generator output)
        std::string cppFile = cppFiles[i];
        SourceFileAttributesParser attributes(cppFile);
        if (!attributes.hasGeneratorOutput())
            continue;

        // confirm we have attributes
        haveAttributes = true;

        // write functions
        generators.writeFunctions(attributes, verbose);

        // track depends
        for (SourceFileAttributesParser::const_iterator
                     it = attributes.begin(); it != attributes.end(); ++it) {
            if (it->name() == kDependsAttribute) {
                for (size_t i = 0; i<it->params().size(); ++i)
                    dependsAttribs.insert(it->params()[i].name());
            }
        }
    }

    // write end
    generators.writeEnd();

    // commit or remove
    std::vector<std::string> updated;
    if (haveAttributes)
        updated = generators.commit(includes);
    else
        updated = generators.remove();

    // print warning if there are depends attributes that don't have
    // corresponding entries in the DESCRIPTION file
    std::vector<std::string> diff;
    std::set_difference(dependsAttribs.begin(), dependsAttribs.end(),
                        depends.begin(), depends.end(),
                        std::back_inserter(diff));
    if (!diff.empty()) {
        std::string msg =
           "The following packages are referenced using Rcpp::depends "
           "attributes however are not listed in the Depends, Imports or "
           "LinkingTo fields of the package DESCRIPTION file: ";
        for (size_t i=0; i<diff.size(); i++) {
            msg += diff[i];
            if (i != (diff.size()-1))
                msg += ", ";
        }
        showWarning(msg);
    }

    // verbose output
    if (verbose) {
        for (size_t i=0; i<updated.size(); i++)
            Rcpp::Rcout << updated[i] << " updated." << std::endl;
    }

    // return files updated
    return Rcpp::wrap<std::vector<std::string> >(updated);
END_RCPP
}