File: pform.cc

package info (click to toggle)
iverilog 12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 30,148 kB
  • sloc: cpp: 109,972; ansic: 62,713; yacc: 10,216; sh: 3,470; vhdl: 3,246; perl: 1,814; makefile: 1,774; python: 78; csh: 2
file content (3444 lines) | stat: -rw-r--r-- 101,323 bytes parent folder | download | duplicates (2)
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
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
/*
 * Copyright (c) 1998-2021 Stephen Williams (steve@icarus.com)
 * Copyright CERN 2013 / Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form 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.
 *
 *    This program 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 this program; if not, write to the Free Software
 *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

# include "config.h"

# include  <cstdarg>
# include  "compiler.h"
# include  "pform.h"
# include  "parse_misc.h"
# include  "parse_api.h"
# include  "PClass.h"
# include  "PEvent.h"
# include  "PPackage.h"
# include  "PUdp.h"
# include  "PGenerate.h"
# include  "PModport.h"
# include  "PSpec.h"
# include  "discipline.h"
# include  <list>
# include  <map>
# include  <cassert>
# include  <stack>
# include  <typeinfo>
# include  <sstream>
# include  <cstring>
# include  <cstdlib>
# include  <cctype>

# include  "ivl_assert.h"
# include  "ivl_alloc.h"

using namespace std;

/*
 * The "// synthesis translate_on/off" meta-comments cause this flag
 * to be turned off or on. The pform_make_behavior and similar
 * functions look at this flag and may choose to add implicit ivl
 * synthesis flags.
 */
static bool pform_mc_translate_flag = true;
void pform_mc_translate_on(bool flag) { pform_mc_translate_flag = flag; }

/*
 * The pform_modules is a map of the modules that have been defined in
 * the top level. This should not contain nested modules/programs.
 * pform_primitives is similar, but for UDP primitives.
 */
map<perm_string,Module*> pform_modules;
map<perm_string,PUdp*> pform_primitives;

/*
 * The pform_units is a list of the SystemVerilog compilation unit scopes.
 * The current compilation unit is the last element in the list. All items
 * declared or defined at the top level (outside any design element) are
 * added to the current compilation unit scope.
 */
vector<PPackage*> pform_units;

static bool is_compilation_unit(LexicalScope*scope)
{
	// A compilation unit is the only scope that doesn't have a parent.
      assert(scope);
      return scope->parent_scope() == 0;
}

std::string vlltype::get_fileline() const
{
      ostringstream buf;
      buf << (text? text : "") << ":" << first_line;
      string res = buf.str();
      return res;

}

static bool is_hex_digit_str(const char *str)
{
      while (*str) {
	    if (!isxdigit(*str)) return false;
	    str++;
      }
      return true;
}

static bool is_dec_digit_str(const char *str)
{
      while (*str) {
	    if (!isdigit(*str)) return false;
	    str++;
      }
      return true;
}

static bool is_oct_digit_str(const char *str)
{
      while (*str) {
	    if (*str < '0' || *str > '7') return false;
	    str++;
      }
      return true;
}

static bool is_bin_digit_str(const char *str)
{
      while (*str) {
	    if (*str != '0' && *str != '1') return false;
	    str++;
      }
      return true;
}

/*
 * Parse configuration file with format <key>=<value>, where key
 * is the hierarchical name of a valid parameter name, and value
 * is the value user wants to assign to. The value should be constant.
 */
void parm_to_defparam_list(const string&param)
{
    char* key;
    char* value;
    unsigned off = param.find('=');
    if (off > param.size()) {
        key = strdup(param.c_str());
        value = (char*)malloc(1);
        *value = '\0';

    } else {
        key = strdup(param.substr(0, off).c_str());
        value = strdup(param.substr(off+1).c_str());
    }

    // Resolve hierarchical name for defparam. Remember
    // to deal with bit select for generate scopes. Bit
    // select expression should be constant integer.
    pform_name_t name;
    char *nkey = key;
    char *ptr = strchr(key, '.');
    while (ptr != 0) {
        *ptr++ = '\0';
        // Find if bit select is applied, this would be something
        // like - scope[2].param = 10
        char *bit_l = strchr(nkey, '[');
        if (bit_l !=0) {
            *bit_l++ = '\0';
            char *bit_r = strchr(bit_l, ']');
            if (bit_r == 0) {
                cerr << "<command line>: error: missing ']' for defparam: " << nkey << endl;
                free(key);
                free(value);
                return;
            }
            *bit_r = '\0';
            int i = 0;
            while (*(bit_l+i) != '\0')
                if (!isdigit(*(bit_l+i++))) {
                    cerr << "<command line>: error: scope index expression is not constant: " << nkey << endl;
                    free(key);
                    free(value);
                    return;
                }
            name_component_t tmp(lex_strings.make(nkey));
            index_component_t index;
            index.sel = index_component_t::SEL_BIT;
            verinum *seln = new verinum(atoi(bit_l));
            PENumber *sel = new PENumber(seln);
            index.msb = sel;
            index.lsb = sel;
            tmp.index.push_back(index);
            name.push_back(tmp);
        }
        else    // no bit select
            name.push_back(name_component_t(lex_strings.make(nkey)));

        nkey = ptr;
        ptr = strchr(nkey, '.');
    }
    name.push_back(name_component_t(lex_strings.make(nkey)));
    free(key);

    // Resolve value to PExpr class. Should support all kind of constant
    // format including based number, dec number, real number and string.

    // Is it a string?
    if (*value == '"') {
	char *buf = strdup (value);
	char *buf_ptr = buf+1;
	// Parse until another '"' or '\0'
	while (*buf_ptr != '"' && *buf_ptr != '\0') {
	    buf_ptr++;
	    // Check for escape, especially '\"', which does not mean the
	    // end of string.
	    if (*buf_ptr == '\\' && *(buf_ptr+1) != '\0')
		buf_ptr += 2;
	}
	if (*buf_ptr == '\0')	// String end without '"'
	    cerr << "<command line>: error: missing close quote of string for defparam: " << name << endl;
	else if (*(buf_ptr+1) != 0) { // '"' appears within string with no escape
	    cerr << buf_ptr << endl;
	    cerr << "<command line>: error: \'\"\' appears within string value for defparam: " << name
		 << ". Ignore characters after \'\"\'" << endl;
	}

	*buf_ptr = '\0';
	buf_ptr = buf+1;
	// Remember to use 'new' to allocate string for PEString
	// because 'delete' is used by its destructor.
	char *nchar = strcpy(new char [strlen(buf_ptr)+1], buf_ptr);
	PExpr* ndec = new PEString(nchar);
	Module::user_defparms.push_back( make_pair(name, ndec) );
	free(buf);
	free(value);
	return;
    }

    // Is it a based number?
    char *num = strchr(value, '\'');
    if (num != 0) {
	verinum *val;
	const char *base = num + 1;
	if (*base == 's' || *base == 'S')
	    base++;
	switch (*base) {
	  case 'h':
	  case 'H':
	    if (is_hex_digit_str(base+1)) {
		val = make_unsized_hex(num);
	    } else {
		cerr << "<command line>: error: invalid digit in hex value specified for defparam: " << name << endl;
		free(value);
		return;
	    }
	    break;
	  case 'd':
	  case 'D':
	    if (is_dec_digit_str(base+1)) {
		val = make_unsized_dec(num);
	    } else {
		cerr << "<command line>: error: invalid digit in decimal value specified for defparam: " << name << endl;
		free(value);
		return;
	    }
	    break;
	  case 'o':
	  case 'O':
	    if (is_oct_digit_str(base+1)) {
		val = make_unsized_octal(num);
	    } else {
		cerr << "<command line>: error: invalid digit in octal value specified for defparam: " << name << endl;
		free(value);
		return;
	    }
	    break;
	  case 'b':
	  case 'B':
	    if (is_bin_digit_str(base+1)) {
		val = make_unsized_binary(num);
	    } else {
		cerr << "<command line>: error: invalid digit in binary value specified for defparam: " << name << endl;
		free(value);
		return;
	    }
	    break;
	  default:
	    cerr << "<command line>: error: invalid numeric base specified for defparam: " << name << endl;
	    free(value);
	    return;
	}
	if (num != value) {  // based number with size
	    *num = 0;
	    if (is_dec_digit_str(value)) {
		verinum *siz = make_unsized_dec(value);
		val = pform_verinum_with_size(siz, val, "<command line>", 0);
	    } else {
		cerr << "<command line>: error: invalid size for value specified for defparam: " << name << endl;
		free(value);
		return;
	    }
	}
	PExpr* ndec = new PENumber(val);
	Module::user_defparms.push_back( make_pair(name, ndec) );
	free(value);
	return;
    }

    // Is it a decimal number?
    num = (value[0] == '-') ? value + 1 : value;
    if (num[0] != '\0' && is_dec_digit_str(num)) {
	verinum *val = make_unsized_dec(num);
	if (value[0] == '-') *val = -(*val);
	PExpr* ndec = new PENumber(val);
	Module::user_defparms.push_back( make_pair(name, ndec) );
	free(value);
	return;
    }

    // Is it a real number?
    char *end = 0;
    double rval = strtod(value, &end);
    if (end != value && *end == 0) {
	verireal *val = new verireal(rval);
	PExpr* nreal = new PEFNumber(val);
	Module::user_defparms.push_back( make_pair(name, nreal) );
	free(value);
	return;
    }

    // None of the above.
    cerr << "<command line>: error: invalid value specified for defparam: " << name << endl;
    free(value);
}

/*
 * The lexor accesses the vl_* variables.
 */
string vl_file = "";

extern int VLparse();

  /* This tracks the current module being processed. There can only be
     exactly one module currently being parsed, since Verilog does not
     allow nested module definitions. */
static list<Module*>pform_cur_module;

bool pform_library_flag = false;

/*
 * Give each unnamed block that has a variable declaration a unique name.
 */
static unsigned scope_unnamed_block_with_decl = 1;

  /* This tracks the current generate scheme being processed. This is
     always within a module. */
static PGenerate*pform_cur_generate = 0;

  /* This indicates whether a new generate construct can be directly
     nested in the current generate construct. */
bool pform_generate_single_item = false;

  /* Blocks within the same conditional generate construct may have
     the same name. Here we collect the set of names used in each
     construct, so they can be added to the local scope without
     conflicting with each other. Generate constructs may nest, so
     we need a stack. */
static list<set<perm_string> > conditional_block_names;

  /* This tracks the current modport list being processed. This is
     always within an interface. */
static PModport*pform_cur_modport = 0;

static NetNet::Type pform_default_nettype = NetNet::WIRE;

/*
 * These variables track the time scale set by the most recent `timescale
 * directive. Time scales set by SystemVerilog timeunit and timeprecision
 * declarations are stored directly in the current lexical scope.
 */
static int pform_time_unit;
static int pform_time_prec;

/*
 * These variables track where the most recent `timescale directive
 * occurred. This allows us to warn about time scales that are inherited
 * from another file.
 */
static char*pform_timescale_file = 0;
static unsigned pform_timescale_line;

/*
 * These variables track whether we can accept new timeunits declarations.
 */
bool allow_timeunit_decl = true;
bool allow_timeprec_decl = true;

// Track whether the current parameter declaration is in a parameter port list
static bool pform_in_parameter_port_list = false;

/*
 * The lexical_scope keeps track of the current lexical scope that is
 * being parsed. The lexical scope may stack, so the current scope may
 * have a parent, that is restored when the current scope ends.
 *
 * Items that have scoped names are put in the lexical_scope object.
 */
static LexicalScope* lexical_scope = 0;

LexicalScope* pform_peek_scope(void)
{
      assert(lexical_scope);
      return lexical_scope;
}

void pform_pop_scope()
{
      LexicalScope*scope = lexical_scope;
      assert(scope);

      map<perm_string,PPackage*>::const_iterator cur;
      for (cur = scope->possible_imports.begin(); cur != scope->possible_imports.end(); ++cur) {
            if (scope->local_symbols.find(cur->first) == scope->local_symbols.end())
                  scope->explicit_imports[cur->first] = cur->second;
      }
      scope->possible_imports.clear();

      lexical_scope = scope->parent_scope();
      assert(lexical_scope);
}

static LexicalScope::lifetime_t find_lifetime(LexicalScope::lifetime_t lifetime)
{
      if (lifetime != LexicalScope::INHERITED)
	    return lifetime;

      return lexical_scope->default_lifetime;
}

static PScopeExtra* find_nearest_scopex(LexicalScope*scope)
{
      PScopeExtra*scopex = dynamic_cast<PScopeExtra*> (scope);
      while (scope && !scopex) {
	    scope = scope->parent_scope();
	    scopex = dynamic_cast<PScopeExtra*> (scope);
      }
      return scopex;
}

static void add_local_symbol(LexicalScope*scope, perm_string name, PNamedItem*item)
{
      assert(scope);

	// Check for conflict with another local symbol.
      map<perm_string,PNamedItem*>::const_iterator cur_sym
	    = scope->local_symbols.find(name);
      if (cur_sym != scope->local_symbols.end()) {
	    cerr << item->get_fileline() << ": error: "
		    "'" << name << "' has already been declared "
		    "in this scope." << endl;
	    cerr << cur_sym->second->get_fileline() << ":      : "
		    "It was declared here as "
		 << cur_sym->second->symbol_type() << "." << endl;
	    error_count += 1;
	    return;
      }

	// Check for conflict with an explicit import.
      map<perm_string,PPackage*>::const_iterator cur_pkg
	    = scope->explicit_imports.find(name);
      if (cur_pkg != scope->explicit_imports.end()) {
	    cerr << item->get_fileline() << ": error: "
		    "'" << name << "' has already been "
		    "imported into this scope from package '"
		 << cur_pkg->second->pscope_name() << "'." << endl;
	    error_count += 1;
	    return;
      }

      scope->local_symbols[name] = item;
}

static PPackage*find_potential_import(const struct vlltype&loc, LexicalScope*scope,
				      perm_string name, bool tf_call, bool make_explicit)
{
      assert(scope);

      PPackage*found_pkg = 0;
      for (list<PPackage*>::const_iterator cur_pkg = scope->potential_imports.begin();
	      cur_pkg != scope->potential_imports.end(); ++cur_pkg) {
	    PPackage*search_pkg = *cur_pkg;
	    map<perm_string,PNamedItem*>::const_iterator cur_sym
		= search_pkg->local_symbols.find(name);
	    if (cur_sym != search_pkg->local_symbols.end()) {
		  if (found_pkg && make_explicit) {
			cerr << loc.get_fileline() << ": error: "
				"Ambiguous use of '" << name << "'. "
				"It is exported by both '"
			      << found_pkg->pscope_name()
			      << "' and by '"
			      << search_pkg->pscope_name()
			      << "'." << endl;
			error_count += 1;
		  } else {
			found_pkg = search_pkg;
			if (make_explicit) {
                              if (tf_call)
			            scope->possible_imports[name] = found_pkg;
                              else
			            scope->explicit_imports[name] = found_pkg;
                        }
		  }
	    }
      }
      return found_pkg;
}

static void check_potential_imports(const struct vlltype&loc, perm_string name, bool tf_call)
{
      LexicalScope*scope = lexical_scope;
      while (scope) {
	    if (scope->local_symbols.find(name) != scope->local_symbols.end())
		  return;
	    if (scope->explicit_imports.find(name) != scope->explicit_imports.end())
		  return;
	    if (find_potential_import(loc, scope, name, tf_call, true))
		  return;

	    scope = scope->parent_scope();
      }
}

/*
 * Set the local time unit/precision. This version is used for setting
 * the time scale for design elements (modules, packages, etc.) and is
 * called after any initial timeunit and timeprecision declarations
 * have been parsed.
 */
void pform_set_scope_timescale(const struct vlltype&loc)
{
      PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
      assert(scope);

      PScopeExtra*parent = find_nearest_scopex(scope->parent_scope());

      bool used_global_timescale = false;
      if (scope->time_unit_is_default) {
            if (is_compilation_unit(scope)) {
                  scope->time_unit = def_ts_units;
            } else if (!is_compilation_unit(parent)) {
                  scope->time_unit = parent->time_unit;
                  scope->time_unit_is_default = parent->time_unit_is_default;
            } else if (pform_timescale_file != 0) {
                  scope->time_unit = pform_time_unit;
                  scope->time_unit_is_default = false;
                  used_global_timescale = true;
            } else /* parent is compilation unit */ {
                  scope->time_unit = parent->time_unit;
                  scope->time_unit_is_default = parent->time_unit_is_default;
            }
      }
      if (scope->time_prec_is_default) {
            if (is_compilation_unit(scope)) {
                  scope->time_precision = def_ts_prec;
            } else if (!is_compilation_unit(parent)) {
                  scope->time_precision = parent->time_precision;
                  scope->time_prec_is_default = parent->time_prec_is_default;
            } else if (pform_timescale_file != 0) {
                  scope->time_precision = pform_time_prec;
                  scope->time_prec_is_default = false;
                  used_global_timescale = true;
            } else {
                  scope->time_precision = parent->time_precision;
                  scope->time_prec_is_default = parent->time_prec_is_default;
            }
      }

      if (gn_system_verilog() && (scope->time_unit < scope->time_precision)) {
	    if (scope->time_unit_is_local || scope->time_prec_is_local) {
		  VLerror("error: A timeprecision is missing or is too large!");
	    }
      } else {
            assert(scope->time_unit >= scope->time_precision);
      }

      if (warn_timescale && used_global_timescale
	  && (strcmp(pform_timescale_file, loc.text) != 0)) {

	    cerr << loc.get_fileline() << ": warning: "
		 << "timescale for " << scope->pscope_name()
		 << " inherited from another file." << endl;
	    cerr << pform_timescale_file << ":" << pform_timescale_line
		 << ": ...: The inherited timescale is here." << endl;
      }

      allow_timeunit_decl = false;
      allow_timeprec_decl = false;
}

/*
 * Set the local time unit/precision. This version is used for setting
 * the time scale for subsidiary items (classes, subroutines, etc.),
 * which simply inherit their time scale from their parent scope.
 */
static void pform_set_scope_timescale(PScope*scope, const PScope*parent)
{
      scope->time_unit            = parent->time_unit;
      scope->time_precision       = parent->time_precision;
      scope->time_unit_is_default = parent->time_unit_is_default;
      scope->time_prec_is_default = parent->time_prec_is_default;
}

PClass* pform_push_class_scope(const struct vlltype&loc, perm_string name)
{
      PClass*class_scope = new PClass(name, lexical_scope);
      class_scope->default_lifetime = LexicalScope::AUTOMATIC;
      FILE_NAME(class_scope, loc);

      PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
      assert(scopex);
      assert(!pform_cur_generate);

      pform_set_scope_timescale(class_scope, scopex);

      scopex->classes[name] = class_scope;
      scopex->classes_lexical .push_back(class_scope);

      lexical_scope = class_scope;
      return class_scope;
}

PPackage* pform_push_package_scope(const struct vlltype&loc, perm_string name,
				   LexicalScope::lifetime_t lifetime)
{
      PPackage*pkg_scope = new PPackage(name, lexical_scope);
      pkg_scope->default_lifetime = find_lifetime(lifetime);
      FILE_NAME(pkg_scope, loc);

      allow_timeunit_decl = true;
      allow_timeprec_decl = true;

      lexical_scope = pkg_scope;
      return pkg_scope;
}

PTask* pform_push_task_scope(const struct vlltype&loc, char*name,
			     LexicalScope::lifetime_t lifetime)
{
      perm_string task_name = lex_strings.make(name);

      LexicalScope::lifetime_t default_lifetime = find_lifetime(lifetime);
      bool is_auto = default_lifetime == LexicalScope::AUTOMATIC;

      PTask*task = new PTask(task_name, lexical_scope, is_auto);
      task->default_lifetime = default_lifetime;
      FILE_NAME(task, loc);

      PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
      assert(scopex);
      if (is_compilation_unit(scopex) && !gn_system_verilog()) {
	    cerr << task->get_fileline() << ": error: task declarations "
		  "must be contained within a module." << endl;
	    error_count += 1;
      }

      pform_set_scope_timescale(task, scopex);

      if (pform_cur_generate) {
	    add_local_symbol(pform_cur_generate, task_name, task);
	    pform_cur_generate->tasks[task_name] = task;
      } else {
	    add_local_symbol(scopex, task_name, task);
	    scopex->tasks[task_name] = task;
      }

      lexical_scope = task;

      return task;
}

PFunction* pform_push_function_scope(const struct vlltype&loc, const char*name,
                                     LexicalScope::lifetime_t lifetime)
{
      perm_string func_name = lex_strings.make(name);

      LexicalScope::lifetime_t default_lifetime = find_lifetime(lifetime);
      bool is_auto = default_lifetime == LexicalScope::AUTOMATIC;

      PFunction*func = new PFunction(func_name, lexical_scope, is_auto);
      func->default_lifetime = default_lifetime;
      FILE_NAME(func, loc);

      PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
      assert(scopex);
      if (is_compilation_unit(scopex) && !gn_system_verilog()) {
	    cerr << func->get_fileline() << ": error: function declarations "
		  "must be contained within a module." << endl;
	    error_count += 1;
      }

      pform_set_scope_timescale(func, scopex);

      if (pform_cur_generate) {
	    add_local_symbol(pform_cur_generate, func_name, func);
	    pform_cur_generate->funcs[func_name] = func;

      } else {
	    add_local_symbol(scopex, func_name, func);
	    scopex->funcs[func_name] = func;
      }

      lexical_scope = func;

      return func;
}

PBlock* pform_push_block_scope(const struct vlltype&loc, char*name,
			       PBlock::BL_TYPE bt)
{
      perm_string block_name;
      if (name) block_name = lex_strings.make(name);
      else {
	      // Create a unique name for this unnamed block.
	    char tmp[32];
	    snprintf(tmp, sizeof tmp, "$unm_blk_%u",
	             scope_unnamed_block_with_decl);
	    block_name = lex_strings.make(tmp);
	    scope_unnamed_block_with_decl += 1;
      }

      PBlock*block = new PBlock(block_name, lexical_scope, bt);
      FILE_NAME(block, loc);
      block->default_lifetime = find_lifetime(LexicalScope::INHERITED);
      if (name) add_local_symbol(lexical_scope, block_name, block);
      lexical_scope = block;

      return block;
}

/*
 * Create a new identifier.
 */
PEIdent* pform_new_ident(const struct vlltype&loc, const pform_name_t&name)
{
      if (gn_system_verilog())
	    check_potential_imports(loc, name.front().name, false);

      return new PEIdent(name);
}

PTrigger* pform_new_trigger(const struct vlltype&loc, PPackage*pkg,
			    const pform_name_t&name)
{
      if (gn_system_verilog())
	    check_potential_imports(loc, name.front().name, false);

      PTrigger*tmp = new PTrigger(pkg, name);
      FILE_NAME(tmp, loc);
      return tmp;
}

PNBTrigger* pform_new_nb_trigger(const struct vlltype&loc,
			         const list<PExpr*>*dly,
			         const pform_name_t&name)
{
      if (gn_system_verilog())
	    check_potential_imports(loc, name.front().name, false);

      PExpr*tmp_dly = 0;
      if (dly) {
	    assert(dly->size() == 1);
	    tmp_dly = dly->front();
      }

      PNBTrigger*tmp = new PNBTrigger(name, tmp_dly);
      FILE_NAME(tmp, loc);
      return tmp;
}

PGenerate* pform_parent_generate(void)
{
      return pform_cur_generate;
}

bool pform_error_in_generate(const vlltype&loc, const char *type)
{
	if (!pform_parent_generate())
		return false;

	VLerror(loc, "error: %s is not allowed in generate block.", type);
	return true;
}

void pform_bind_attributes(map<perm_string,PExpr*>&attributes,
			   list<named_pexpr_t>*attr, bool keep_attrs)
{
      if (attr == 0)
	    return;

      while (! attr->empty()) {
	    named_pexpr_t tmp = attr->front();
	    attr->pop_front();
	    attributes[tmp.name] = tmp.parm;
      }
      if (!keep_attrs)
	    delete attr;
}

bool pform_in_program_block()
{
      if (pform_cur_module.empty())
	    return false;
      if (pform_cur_module.front()->program_block)
	    return true;
      return false;
}

bool pform_in_interface()
{
      if (pform_cur_module.empty())
	    return false;
      if (pform_cur_module.front()->is_interface)
	    return true;
      return false;
}

static bool pform_at_module_level()
{
      return (lexical_scope == pform_cur_module.front())
          || (lexical_scope == pform_cur_generate);
}

PWire*pform_get_wire_in_scope(perm_string name)
{
      return lexical_scope->wires_find(name);
}

static void pform_put_wire_in_scope(perm_string name, PWire*net)
{
      add_local_symbol(lexical_scope, name, net);
      lexical_scope->wires[name] = net;
}

void pform_put_enum_type_in_scope(enum_type_t*enum_set)
{
      if (std::find(lexical_scope->enum_sets.begin(),
		    lexical_scope->enum_sets.end(), enum_set) !=
          lexical_scope->enum_sets.end())
	    return;

      set<perm_string> enum_names;
      list<named_pexpr_t>::const_iterator cur;
      for (cur = enum_set->names->begin(); cur != enum_set->names->end(); ++cur) {
	    if (enum_names.count(cur->name)) {
		  cerr << enum_set->get_fileline() << ": error: "
			  "Duplicate enumeration name '"
		       << cur->name << "'." << endl;
		  error_count += 1;
	    } else {
		  add_local_symbol(lexical_scope, cur->name, enum_set);
		  enum_names.insert(cur->name);
	    }
      }

      lexical_scope->enum_sets.push_back(enum_set);
}

static typedef_t *pform_get_typedef(const struct vlltype&loc, perm_string name)
{
      typedef_t *&td = lexical_scope->typedefs[name];
      if (!td) {
	    td = new typedef_t(name);
	    FILE_NAME(td, loc);
	    add_local_symbol(lexical_scope, name, td);
      }
      return td;
}

void pform_forward_typedef(const struct vlltype&loc, perm_string name,
			   enum typedef_t::basic_type basic_type)
{
      typedef_t *td = pform_get_typedef(loc, name);

      if (!td->set_basic_type(basic_type)) {
	    cout << loc << " error: Incompatible basic type `" << basic_type
	         << "` for `" << name
		 << "`. Previously declared in this scope as `"
		 << td->get_basic_type() << "` at " << td->get_fileline() << "."
	         << endl;
	    error_count++;
      }
}

void pform_set_typedef(const struct vlltype&loc, perm_string name,
		       data_type_t*data_type,
		       std::list<pform_range_t>*unp_ranges)
{
      typedef_t *td = pform_get_typedef(loc, name);

      if(unp_ranges)
	    data_type = new uarray_type_t(data_type, unp_ranges);

      if (!td->set_data_type(data_type)) {
	    cerr << loc << " error: Type identifier `" << name
		 << "` has already been declared in this scope at "
		 << td->get_data_type()->get_fileline() << "."
		 << endl;
	    error_count++;
	    delete data_type;
      }
}

void pform_set_type_referenced(const struct vlltype&loc, const char*name)
{
      perm_string lex_name = lex_strings.make(name);
      check_potential_imports(loc, lex_name, false);
}

typedef_t* pform_test_type_identifier(const struct vlltype&loc, const char*txt)
{
      perm_string name = lex_strings.make(txt);

      LexicalScope*cur_scope = lexical_scope;
      do {
	    LexicalScope::typedef_map_t::iterator cur;

	      // First look to see if this identifier is imported from
	      // a package. If it is, see if it is a type in that
	      // package. If it is, then great. If imported as
	      // something other than a type, then give up now because
	      // the name has at least shadowed any other possible
	      // meaning for this name.
	    map<perm_string,PPackage*>::iterator cur_pkg;
	    cur_pkg = cur_scope->explicit_imports.find(name);
	    if (cur_pkg != cur_scope->explicit_imports.end()) {
		  PPackage*pkg = cur_pkg->second;
		  cur = pkg->typedefs.find(name);
		  if (cur != pkg->typedefs.end())
			return cur->second;

		    // Not a type. Give up.
		  return 0;
	    }

	    cur = cur_scope->typedefs.find(name);
	    if (cur != cur_scope->typedefs.end())
		  return cur->second;

            PPackage*pkg = find_potential_import(loc, cur_scope, name, false, false);
            if (pkg) {
	          cur = pkg->typedefs.find(name);
	          if (cur != pkg->typedefs.end())
		        return cur->second;

		    // Not a type. Give up.
		  return 0;
            }

	    cur_scope = cur_scope->parent_scope();
      } while (cur_scope);

      return 0;
}

PECallFunction* pform_make_call_function(const struct vlltype&loc,
					 const pform_name_t&name,
					 const list<PExpr*>&parms)
{
      if (gn_system_verilog())
	    check_potential_imports(loc, name.front().name, true);

      PECallFunction*tmp = new PECallFunction(name, parms);
      FILE_NAME(tmp, loc);
      return tmp;
}

PCallTask* pform_make_call_task(const struct vlltype&loc,
				const pform_name_t&name,
				const list<PExpr*>&parms)
{
      if (gn_system_verilog())
	    check_potential_imports(loc, name.front().name, true);

      PCallTask*tmp = new PCallTask(name, parms);
      FILE_NAME(tmp, loc);
      return tmp;
}

void pform_make_var(const struct vlltype&loc,
		    std::list<decl_assignment_t*>*assign_list,
		    data_type_t*data_type, std::list<named_pexpr_t>*attr)
{
      static const struct str_pair_t str = { IVL_DR_STRONG, IVL_DR_STRONG };

      pform_makewire(loc, 0, str, assign_list, NetNet::REG, data_type, attr);
}

void pform_make_foreach_declarations(const struct vlltype&loc,
				     std::list<perm_string>*loop_vars)
{
      list<decl_assignment_t*>assign_list;
      for (list<perm_string>::const_iterator cur = loop_vars->begin()
		 ; cur != loop_vars->end() ; ++ cur) {
	    if (cur->nil())
		  continue;
	    decl_assignment_t*tmp_assign = new decl_assignment_t;
	    tmp_assign->name = lex_strings.make(*cur);
	    assign_list.push_back(tmp_assign);
      }

      pform_make_var(loc, &assign_list, &size_type);
}

PForeach* pform_make_foreach(const struct vlltype&loc,
			     char*name,
			     list<perm_string>*loop_vars,
			     Statement*stmt)
{
      perm_string use_name = lex_strings.make(name);
      delete[]name;

      if (loop_vars==0 || loop_vars->empty()) {
	    cerr << loc.get_fileline() << ": error: "
		 << "No loop variables at all in foreach index." << endl;
	    error_count += 1;
      }

      ivl_assert(loc, loop_vars);
      PForeach*fe = new PForeach(use_name, *loop_vars, stmt);
      FILE_NAME(fe, loc);

      delete loop_vars;

      return fe;
}

static void pform_put_behavior_in_scope(PProcess*pp)
{
      lexical_scope->behaviors.push_back(pp);
}

void pform_put_behavior_in_scope(AProcess*pp)
{
      lexical_scope->analog_behaviors.push_back(pp);
}

void pform_set_default_nettype(NetNet::Type type,
			       const char*file, unsigned lineno)
{
      pform_default_nettype = type;

      if (! pform_cur_module.empty()) {
	    cerr << file<<":"<<lineno << ": error: "
		 << "`default_nettype directives must appear" << endl;
	    cerr << file<<":"<<lineno << ":      : "
		 << "outside module definitions. The containing" << endl;
	    cerr << file<<":"<<lineno << ":      : "
		 << "module " << pform_cur_module.back()->mod_name()
		 << " starts on line "
		 << pform_cur_module.back()->get_fileline() << "." << endl;
	    error_count += 1;
      }
}

static void pform_declare_implicit_nets(PExpr*expr)
{
	/* If implicit net creation is turned off, then stop now. */
      if (pform_default_nettype == NetNet::NONE)
	    return;

      if (expr)
            expr->declare_implicit_nets(lexical_scope, pform_default_nettype);
}

/*
 * The lexor calls this function to set the active timescale when it
 * detects a `timescale directive. The function saves the directive
 * values (for use by subsequent design elements) and if warnings are
 * enabled checks to see if some design elements have no timescale.
 */
void pform_set_timescale(int unit, int prec,
			 const char*file, unsigned lineno)
{
      assert(unit >= prec);
      pform_time_unit = unit;
      pform_time_prec = prec;

      if (pform_timescale_file) {
	    free(pform_timescale_file);
      }

      if (file) pform_timescale_file = strdup(file);
      else pform_timescale_file = 0;
      pform_timescale_line = lineno;
}

bool get_time_unit(const char*cp, int &unit)
{
	const char *c;
	bool        rc = true;

	if (strchr(cp, '_')) {
		VLerror(yylloc, "error: Invalid timeunit constant ('_' is not "
				"supported).");
		return false;
	}

	c = strpbrk(cp, "munpfs");
	if (!c)
		return false;

	if (*c == 's')
		unit = 0;
	else if (!strncmp(c, "ms", 2))
		unit = -3;
	else if (!strncmp(c, "us", 2))
		unit = -6;
	else if (!strncmp(c, "ns", 2))
		unit = -9;
	else if (!strncmp(c, "ps", 2))
		unit = -12;
	else if (!strncmp(c, "fs", 2))
		unit = -15;
	else {
		rc = false;

		ostringstream msg;
		msg << "error: Invalid timeunit scale '" << cp << "'.";
		VLerror(msg.str().c_str());
	}

	return rc;
}

/*
 * Get a timeunit or timeprecision value from a string.  This is
 * similar to the code in lexor.lex for the `timescale directive.
 */
static bool get_time_unit_prec(const char*cp, int &res, bool is_unit)
{
	/* We do not support a '_' in these time constants. */
      if (strchr(cp, '_')) {
	    if (is_unit) {
		  VLerror(yylloc, "error: Invalid timeunit constant ('_' "
		                  "is not supported).");
	    } else {
		  VLerror(yylloc, "error: Invalid timeprecision constant ('_' "
		                  "is not supported).");
	    }
	    return true;
      }

	/* Check for the 1 digit. */
      if (*cp != '1') {
	    if (is_unit) {
		  VLerror(yylloc, "error: Invalid timeunit constant "
                                  "(1st digit).");
	    } else {
		  VLerror(yylloc, "error: Invalid timeprecision constant "
                                  "(1st digit).");
	    }
	    return true;
      }
      cp += 1;

	/* Check the number of zeros after the 1. */
      res = strspn(cp, "0");
      if (res > 2) {
	    if (is_unit) {
		  VLerror(yylloc, "error: Invalid timeunit constant "
		                  "(number of zeros).");
	    } else {
		  VLerror(yylloc, "error: Invalid timeprecision constant "
		                  "(number of zeros).");
	    }
	    return true;
      }
      cp += res;

	/* Now process the scaling string. */
      if (strncmp("s", cp, 1) == 0) {
	    res -= 0;
	    return false;

      } else if (strncmp("ms", cp, 2) == 0) {
	    res -= 3;
	    return false;

      } else if (strncmp("us", cp, 2) == 0) {
	    res -= 6;
	    return false;

      } else if (strncmp("ns", cp, 2) == 0) {
	    res -= 9;
	    return false;

      } else if (strncmp("ps", cp, 2) == 0) {
	    res -= 12;
	    return false;

      } else if (strncmp("fs", cp, 2) == 0) {
	    res -= 15;
	    return false;

      }

      ostringstream msg;
      msg << "error: Invalid ";
      if (is_unit) msg << "timeunit";
      else msg << "timeprecision";
      msg << " scale '" << cp << "'.";
      VLerror(msg.str().c_str());
      return true;
}

void pform_set_timeunit(const char*txt, bool initial_decl)
{
      int val;

      if (get_time_unit_prec(txt, val, true)) return;

      PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
      if (!scope)
	    return;

      if (initial_decl) {
            scope->time_unit = val;
            scope->time_unit_is_local = true;
            scope->time_unit_is_default = false;
            allow_timeunit_decl = false;
      } else if (!scope->time_unit_is_local) {
            VLerror(yylloc, "error: Repeat timeunit found and the initial "
                            "timeunit for this scope is missing.");
      } else if (scope->time_unit != val) {
            VLerror(yylloc, "error: Repeat timeunit does not match the "
                            "initial timeunit for this scope.");
      }
}

int pform_get_timeunit()
{
      PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
      assert(scopex);
      return scopex->time_unit;
}

int pform_get_timeprec()
{
      PScopeExtra*scopex = find_nearest_scopex(lexical_scope);
      assert(scopex);
      return scopex->time_precision;
}

void pform_set_timeprec(const char*txt, bool initial_decl)
{
      int val;

      if (get_time_unit_prec(txt, val, false)) return;

      PScopeExtra*scope = dynamic_cast<PScopeExtra*>(lexical_scope);
      if (!scope)
	    return;

      if (initial_decl) {
            scope->time_precision = val;
            scope->time_prec_is_local = true;
            scope->time_prec_is_default = false;
            allow_timeprec_decl = false;
      } else if (!scope->time_prec_is_local) {
            VLerror(yylloc, "error: Repeat timeprecision found and the initial "
                            "timeprecision for this scope is missing.");
      } else if (scope->time_precision != val) {
            VLerror(yylloc, "error: Repeat timeprecision does not match the "
                            "initial timeprecision for this scope.");
      }
}

verinum* pform_verinum_with_size(verinum*siz, verinum*val,
				 const char*file, unsigned lineno)
{
      assert(siz->is_defined());
      unsigned long size = siz->as_ulong();

      if (size == 0) {
	    cerr << file << ":" << lineno << ": error: Sized numeric constant "
		    "must have a size greater than zero." << endl;
	    error_count += 1;
      }

      verinum::V pad;

      if (val->len() == 0) {
	    pad = verinum::Vx;
      } else {

	    switch (val->get(val->len()-1)) {
		case verinum::Vz:
		  pad = verinum::Vz;
		  break;
		case verinum::Vx:
		  pad = verinum::Vx;
		  break;
		default:
		  pad = verinum::V0;
		  break;
	    }
      }

      verinum*res = new verinum(pad, size, true);

      unsigned copy = val->len();
      if (res->len() < copy)
	    copy = res->len();

      for (unsigned idx = 0 ;  idx < copy ;  idx += 1) {
	    res->set(idx, val->get(idx));
      }

      res->has_sign(val->has_sign());

      bool trunc_flag = false;
      for (unsigned idx = copy ;  idx < val->len() ;  idx += 1) {
	    if (val->get(idx) != pad) {
		  trunc_flag = true;
		  break;
	    }
      }

      if (trunc_flag) {
	    cerr << file << ":" << lineno << ": warning: Numeric constant "
		 << "truncated to " << copy << " bits." << endl;
      }

      delete siz;
      delete val;
      return res;
}

void pform_startmodule(const struct vlltype&loc, const char*name,
		       bool program_block, bool is_interface,
		       LexicalScope::lifetime_t lifetime,
		       list<named_pexpr_t>*attr)
{
      if (! pform_cur_module.empty() && !gn_system_verilog()) {
	    cerr << loc << ": error: Module definition " << name
		 << " cannot nest into module " << pform_cur_module.front()->mod_name() << "." << endl;
	    error_count += 1;
      }


      if (lifetime != LexicalScope::INHERITED) {
	    pform_requires_sv(loc, "Default subroutine lifetime");
      }

      if (gn_system_verilog() && ! pform_cur_module.empty()) {
	    if (pform_cur_module.front()->program_block) {
		  cerr << loc << ": error: module, program, or interface "
				 "declarations are not allowed in program "
				 "blocks." << endl;
		  error_count += 1;
	    }
	    if (pform_cur_module.front()->is_interface
		&& !(program_block || is_interface)) {
		  cerr << loc << ": error: module declarations are not "
				 "allowed in interfaces." << endl;
		  error_count += 1;
	    }
      }

      perm_string lex_name = lex_strings.make(name);
      Module*cur_module = new Module(lexical_scope, lex_name);
      cur_module->program_block = program_block;
      cur_module->is_interface = is_interface;
      cur_module->default_lifetime = find_lifetime(lifetime);

      FILE_NAME(cur_module, loc);

      cur_module->library_flag = pform_library_flag;

      pform_cur_module.push_front(cur_module);

      allow_timeunit_decl = true;
      allow_timeprec_decl = true;

      pform_generate_single_item = false;

      add_local_symbol(lexical_scope, lex_name, cur_module);

      lexical_scope = cur_module;

      pform_bind_attributes(cur_module->attributes, attr);
}

void pform_start_parameter_port_list()
{
      pform_in_parameter_port_list = true;
      pform_peek_scope()->has_parameter_port_list = true;
}

void pform_end_parameter_port_list()
{
      pform_in_parameter_port_list = false;
}

/*
 * This function is called by the parser to make a simple port
 * reference. This is a name without a .X(...), so the internal name
 * should be generated to be the same as the X.
 */
Module::port_t* pform_module_port_reference(const struct vlltype&loc,
					    perm_string name)
{
      Module::port_t*ptmp = new Module::port_t;
      PEIdent*tmp = new PEIdent(name);
      FILE_NAME(tmp, loc);
      ptmp->name = name;
      ptmp->expr.push_back(tmp);
      ptmp->default_value = 0;

      return ptmp;
}

void pform_module_set_ports(vector<Module::port_t*>*ports)
{
      assert(! pform_cur_module.empty());

	/* The parser parses ``module foo()'' as having one
	   unconnected port, but it is really a module with no
	   ports. Fix it up here. */
      if (ports && (ports->size() == 1) && ((*ports)[0] == 0)) {
	    delete ports;
	    ports = 0;
      }

      if (ports != 0) {
	    pform_cur_module.front()->ports = *ports;
	    delete ports;
      }
}

void pform_endmodule(const char*name, bool inside_celldefine,
                     Module::UCDriveType uc_drive_def)
{
	// The parser will not call pform_endmodule() without first
	// calling pform_startmodule(). Thus, it is impossible for the
	// pform_cur_module stack to be empty at this point.
      assert(! pform_cur_module.empty());
      Module*cur_module  = pform_cur_module.front();
      pform_cur_module.pop_front();
      perm_string mod_name = cur_module->mod_name();

	// Oops, there may be some sort of nesting problem. If
	// SystemVerilog is activated, it is possible for modules to
	// be nested. But if the nested module is broken, the parser
	// will recover and treat is as an invalid module item,
	// leaving the pform_cur_module stack in an inconsistent
	// state. For example, this:
	//    module foo;
	//      module bar blah blab blah error;
	//    endmodule
	// may leave the pform_cur_module stack with the dregs of the
	// bar module. Try to find the foo module in the stack, and
	// print error messages as we go.
      if (strcmp(name, mod_name) != 0) {
	    while (!pform_cur_module.empty()) {
		  Module*tmp_module = pform_cur_module.front();
		  perm_string tmp_name = tmp_module->mod_name();
		  pform_cur_module.pop_front();
		  ostringstream msg;
		  msg << "error: Module " << mod_name
		      << " was nested within " << tmp_name
		      << " but broken.";
		  VLerror(msg.str().c_str());

		  ivl_assert(*cur_module, lexical_scope == cur_module);
		  pform_pop_scope();
		  delete cur_module;

		  cur_module = tmp_module;
		  mod_name = tmp_name;
		  if (strcmp(name, mod_name) == 0)
			break;
	    }
      }
      assert(strcmp(name, mod_name) == 0);

      cur_module->is_cell = inside_celldefine;
      cur_module->uc_drive = uc_drive_def;

	// If this is a root module, then there is no parent module
	// and we try to put this newly defined module into the global
	// root list of modules. Otherwise, this is a nested module
	// and we put it into the parent module scope to be elaborated
	// if needed.
      map<perm_string,Module*>&use_module_map = (pform_cur_module.empty())
	    ? pform_modules
	    : pform_cur_module.front()->nested_modules;

      map<perm_string,Module*>::const_iterator test =
	    use_module_map.find(mod_name);

      if (test != use_module_map.end()) {
	    ostringstream msg;
	    msg << "error: Module " << name << " was already declared here: "
		<< test->second->get_fileline() << endl;
	    VLerror(msg.str().c_str());
      } else {
	    use_module_map[mod_name] = cur_module;
      }

	// The current lexical scope should be this module by now.
      ivl_assert(*cur_module, lexical_scope == cur_module);
      pform_pop_scope();
}

void pform_genvars(const struct vlltype&li, list<perm_string>*names)
{
      list<perm_string>::const_iterator cur;
      for (cur = names->begin(); cur != names->end() ; *cur++) {
	    PGenvar*genvar = new PGenvar();
	    FILE_NAME(genvar, li);

	    if (pform_cur_generate) {
		  add_local_symbol(pform_cur_generate, *cur, genvar);
		  pform_cur_generate->genvars[*cur] = genvar;
	    } else {
		  add_local_symbol(pform_cur_module.front(), *cur, genvar);
		  pform_cur_module.front()->genvars[*cur] = genvar;
	    }
      }

      delete names;
}

static unsigned detect_directly_nested_generate()
{
      if (pform_cur_generate && pform_generate_single_item)
	    switch (pform_cur_generate->scheme_type) {
		case PGenerate::GS_CASE_ITEM:
		  // fallthrough
		case PGenerate::GS_CONDIT:
		  // fallthrough
		case PGenerate::GS_ELSE:
		  pform_cur_generate->directly_nested = true;
		  return pform_cur_generate->id_number;
		default:
		  break;
	    }

      return ++lexical_scope->generate_counter;
}

void pform_start_generate_for(const struct vlltype&li,
			      bool local_index,
			      char*ident1, PExpr*init,
			      PExpr*test,
			      char*ident2, PExpr*next)
{
      PGenerate*gen = new PGenerate(lexical_scope, ++lexical_scope->generate_counter);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_LOOP;

      pform_cur_generate->local_index = local_index;
      pform_cur_generate->loop_index = lex_strings.make(ident1);
      pform_cur_generate->loop_init = init;
      pform_cur_generate->loop_test = test;
      pform_cur_generate->loop_step = next;

      delete[]ident1;
      delete[]ident2;
}

void pform_start_generate_if(const struct vlltype&li, PExpr*test)
{
      unsigned id_number = detect_directly_nested_generate();

      PGenerate*gen = new PGenerate(lexical_scope, id_number);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_CONDIT;

      pform_cur_generate->loop_init = 0;
      pform_cur_generate->loop_test = test;
      pform_cur_generate->loop_step = 0;

      conditional_block_names.push_front(set<perm_string>());
}

void pform_start_generate_else(const struct vlltype&li)
{
      assert(pform_cur_generate);
      assert(pform_cur_generate->scheme_type == PGenerate::GS_CONDIT);

      PGenerate*cur = pform_cur_generate;
      pform_endgenerate(false);

      PGenerate*gen = new PGenerate(lexical_scope, cur->id_number);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_ELSE;

      pform_cur_generate->loop_init = 0;
      pform_cur_generate->loop_test = cur->loop_test;
      pform_cur_generate->loop_step = 0;
}

/*
 * The GS_CASE version of the PGenerate contains only case items. The
 * items in turn contain the generated items themselves.
 */
void pform_start_generate_case(const struct vlltype&li, PExpr*expr)
{
      unsigned id_number = detect_directly_nested_generate();

      PGenerate*gen = new PGenerate(lexical_scope, id_number);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_CASE;

      pform_cur_generate->loop_init = 0;
      pform_cur_generate->loop_test = expr;
      pform_cur_generate->loop_step = 0;

      conditional_block_names.push_front(set<perm_string>());
}

/*
 * The named block generate case.
 */
void pform_start_generate_nblock(const struct vlltype&li, char*name)
{
      PGenerate*gen = new PGenerate(lexical_scope, ++lexical_scope->generate_counter);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_NBLOCK;

      pform_cur_generate->loop_init = 0;
      pform_cur_generate->loop_test = 0;
      pform_cur_generate->loop_step = 0;

      pform_cur_generate->scope_name = lex_strings.make(name);
      delete[]name;

      add_local_symbol(pform_cur_generate->parent_scope(),
                       pform_cur_generate->scope_name,
                       pform_cur_generate);
}

/*
 * The generate case item is a special case schema that takes its id
 * from the case schema that it is a part of. The idea is that the
 * case schema can only instantiate exactly one item, so the items
 * need not have a unique number.
 */
void pform_generate_case_item(const struct vlltype&li, list<PExpr*>*expr_list)
{
      assert(pform_cur_generate);
      assert(pform_cur_generate->scheme_type == PGenerate::GS_CASE);

      PGenerate*gen = new PGenerate(lexical_scope, pform_cur_generate->id_number);
      lexical_scope = gen;

      FILE_NAME(gen, li);

      gen->directly_nested = pform_cur_generate->directly_nested;

      pform_cur_generate = gen;

      pform_cur_generate->scheme_type = PGenerate::GS_CASE_ITEM;

      pform_cur_generate->loop_init = 0;
      pform_cur_generate->loop_test = 0;
      pform_cur_generate->loop_step = 0;

      if (expr_list != 0) {
	    list<PExpr*>::iterator expr_cur = expr_list->begin();
	    pform_cur_generate->item_test.resize(expr_list->size());
	    for (unsigned idx = 0 ; idx < expr_list->size() ; idx += 1) {
		  pform_cur_generate->item_test[idx] = *expr_cur;
		  ++ expr_cur;
	    }
	    assert(expr_cur == expr_list->end());
      }
}

void pform_generate_block_name(char*name)
{
      assert(pform_cur_generate != 0);
      assert(pform_cur_generate->scope_name == 0);
      perm_string scope_name = lex_strings.make(name);
      pform_cur_generate->scope_name = scope_name;

      if (pform_cur_generate->scheme_type == PGenerate::GS_CONDIT
       || pform_cur_generate->scheme_type == PGenerate::GS_ELSE
       || pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM) {

            if (conditional_block_names.front().count(scope_name))
                  return;

            conditional_block_names.front().insert(scope_name);
      }

      LexicalScope*parent_scope = pform_cur_generate->parent_scope();
      assert(parent_scope);
      if (pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM)
	      // Skip over the PGenerate::GS_CASE container.
	    parent_scope = parent_scope->parent_scope();

      add_local_symbol(parent_scope, scope_name, pform_cur_generate);
}

void pform_endgenerate(bool end_conditional)
{
      assert(pform_cur_generate != 0);
      assert(! pform_cur_module.empty());

      if (end_conditional)
            conditional_block_names.pop_front();

	// If there is no explicit block name then generate a temporary
	// name. This will be replaced by the correct name later, once
	// we know all the explicit names in the surrounding scope. If
	// the naming scheme used here is changed, PGenerate::elaborate
	// must be changed to match.
      if (pform_cur_generate->scope_name == 0) {
	    char tmp[16];
	    snprintf(tmp, sizeof tmp, "$gen%u", pform_cur_generate->id_number);
	    pform_cur_generate->scope_name = lex_strings.make(tmp);
      }

	// The current lexical scope should be this generate construct by now
      ivl_assert(*pform_cur_generate, lexical_scope == pform_cur_generate);
      pform_pop_scope();

      PGenerate*parent_generate = dynamic_cast<PGenerate*>(lexical_scope);
      if (parent_generate) {
	    assert(pform_cur_generate->scheme_type == PGenerate::GS_CASE_ITEM
		   || parent_generate->scheme_type != PGenerate::GS_CASE);
	    parent_generate->generate_schemes.push_back(pform_cur_generate);
      } else {
	    assert(pform_cur_generate->scheme_type != PGenerate::GS_CASE_ITEM);
	    pform_cur_module.front()->generate_schemes.push_back(pform_cur_generate);
      }
      pform_cur_generate = parent_generate;
}

void pform_make_elab_task(const struct vlltype&li,
                          perm_string name,
                          const list<PExpr*>&params)
{
      PCallTask*elab_task = new PCallTask(name, params);
      FILE_NAME(elab_task, li);

      lexical_scope->elab_tasks.push_back(elab_task);
}

MIN_TYP_MAX min_typ_max_flag = TYP;
unsigned min_typ_max_warn = 10;

PExpr* pform_select_mtm_expr(PExpr*min, PExpr*typ, PExpr*max)
{
      PExpr*res = 0;

      switch (min_typ_max_flag) {
	  case MIN:
	    res = min;
	    delete typ;
	    delete max;
	    break;
	  case TYP:
	    res = typ;
	    delete min;
	    delete max;
	    break;
	  case MAX:
	    res = max;
	    delete min;
	    delete typ;
	    break;
      }

      if (min_typ_max_warn > 0) {
	    cerr << res->get_fileline() << ": warning: Choosing ";
	    switch (min_typ_max_flag) {
		case MIN:
		  cerr << "min";
		  break;
		case TYP:
		  cerr << "typ";
		  break;
		case MAX:
		  cerr << "max";
		  break;
	    }

	    cerr << " expression." << endl;
	    min_typ_max_warn -= 1;
      }

      return res;
}

static void process_udp_table(PUdp*udp, list<string>*table,
			      const struct vlltype&loc)
{
      const bool synchronous_flag = udp->sequential;

	/* Interpret and check the table entry strings, to make sure
	   they correspond to the inputs, output and output type. Make
	   up vectors for the fully interpreted result that can be
	   placed in the PUdp object.

	   The table strings are made up by the parser to be two or
	   three substrings separated by ';', i.e.:

	   0101:1:1  (synchronous device entry)
	   0101:0    (combinational device entry)

	   The parser doesn't check that we got the right kind here,
	   so this loop must watch out. */
      std::vector<string> &input   = udp->tinput;
      std::vector<char>   &current = udp->tcurrent;
      std::vector<char>   &output  = udp->toutput;

      input.resize(table->size());
      current.resize(table->size());
      output.resize(table->size());

      { unsigned idx = 0;
        for (list<string>::iterator cur = table->begin()
		   ; cur != table->end() ; ++ cur , idx += 1) {
	      string tmp = *cur;

		/* Pull the input values from the string. */
	      assert(tmp.find(':') == (udp->ports.size() - 1));
	      input[idx] = tmp.substr(0, udp->ports.size()-1);
	      tmp = tmp.substr(udp->ports.size()-1);

	      assert(tmp[0] == ':');

		/* If this is a synchronous device, get the current
		   output string. */
	      if (synchronous_flag) {
		    if (tmp.size() != 4) {
			  cerr << loc << ": error: "
			       << "Invalid table format for"
			       << " sequential primitive." << endl;
			  error_count += 1;
			  break;
		    }
		    assert(tmp.size() == 4);
		    current[idx] = tmp[1];
		    tmp = tmp.substr(2);

	      } else if (tmp.size() != 2) {
		  cerr << loc << ": error: "
		       << "Invalid table format for"
		       << " combinational primitive." << endl;
		  error_count += 1;
		  break;
	      }

		/* Finally, extract the desired output. */
	      assert(tmp.size() == 2);
	      output[idx] = tmp[1];
	}
      }

}

void pform_make_udp(const struct vlltype&loc, perm_string name,
		    list<perm_string>*parms, vector<PWire*>*decl,
		    list<string>*table, Statement*init_expr)
{
      unsigned local_errors = 0;
      assert(!parms->empty());

      assert(decl);

	/* Put the declarations into a map, so that I can check them
	   off with the parameters in the list. If the port is already
	   in the map, merge the port type. I will rebuild a list
	   of parameters for the PUdp object. */
      map<perm_string,PWire*> defs;
      for (unsigned idx = 0 ;  idx < decl->size() ;  idx += 1) {

	    perm_string port_name = (*decl)[idx]->basename();

	    if (PWire*cur = defs[port_name]) {
		  bool rc = true;
		  assert((*decl)[idx]);
		  if ((*decl)[idx]->get_port_type() != NetNet::PIMPLICIT) {
			rc = cur->set_port_type((*decl)[idx]->get_port_type());
			assert(rc);
		  }
		  if ((*decl)[idx]->get_wire_type() != NetNet::IMPLICIT) {
			rc = cur->set_wire_type((*decl)[idx]->get_wire_type());
			assert(rc);
		  }

	    } else {
		  defs[port_name] = (*decl)[idx];
	    }
      }


	/* Put the parameters into a vector of wire descriptions. Look
	   in the map for the definitions of the name. In this loop,
	   the parms list in the list of ports in the port list of the
	   UDP declaration, and the defs map maps that name to a
	   PWire* created by an input or output declaration. */
      std::vector<PWire*> pins(parms->size());
      std::vector<perm_string> pin_names(parms->size());
      { list<perm_string>::iterator cur;
        unsigned idx;
        for (cur = parms->begin(), idx = 0
		   ; cur != parms->end()
		   ; ++ idx, ++ cur) {
	      pins[idx] = defs[*cur];
	      pin_names[idx] = *cur;
	}
      }

	/* Check that the output is an output and the inputs are
	   inputs. I can also make sure that only the single output is
	   declared a register, if anything. The possible errors are:

	      -- an input port (not the first) is missing an input
	         declaration.

	      -- An input port is declared output.

	*/
      assert(pins.size() > 0);
      do {
	    if (pins[0] == 0) {
		  cerr << loc << ": error: "
		       << "Output port of primitive " << name
		       << " missing output declaration." << endl;
		  cerr << loc << ":      : "
		       << "Try: output " << pin_names[0] << ";"
		       << endl;
		  error_count += 1;
		  local_errors += 1;
		  break;
	    }
	    if (pins[0]->get_port_type() != NetNet::POUTPUT) {
		  cerr << loc << ": error: "
		       << "The first port of a primitive"
		       << " must be an output." << endl;
		  cerr << loc << ":      : "
		       << "Try: output " << pin_names[0] << ";"
		       << endl;
		  error_count += 1;
		  local_errors += 1;
		  break;;
	    }
      } while (0);

      for (unsigned idx = 1 ;  idx < pins.size() ;  idx += 1) {
	    if (pins[idx] == 0) {
		  cerr << loc << ": error: "
		       << "Port " << (idx+1)
		       << " of primitive " << name << " missing"
		       << " input declaration." << endl;
		  cerr << loc << ":      : "
		       << "Try: input " << pin_names[idx] << ";"
		       << endl;
		  error_count += 1;
		  local_errors += 1;
		  continue;
	    }
	    if (pins[idx]->get_port_type() != NetNet::PINPUT) {
		  cerr << loc << ": error: "
		       << "Input port " << (idx+1)
		       << " of primitive " << name
		       << " has an output (or missing) declaration." << endl;
		  cerr << loc << ":      : "
		       << "Note that only the first port can be an output."
		       << endl;
		  cerr << loc << ":      : "
		       << "Try \"input " << name << ";\""
		       << endl;
		  error_count += 1;
		  local_errors += 1;
		  continue;
	    }

	    if (pins[idx]->get_wire_type() == NetNet::REG) {
		  cerr << loc << ": error: "
		       << "Port " << (idx+1)
		       << " of primitive " << name << " is an input port"
		       << " with a reg declaration." << endl;
		  cerr << loc << ":      : "
		       << "primitive inputs cannot be reg."
		       << endl;
		  error_count += 1;
		  local_errors += 1;
		  continue;
	    }
      }

      if (local_errors > 0) {
	    delete parms;
	    delete decl;
	    delete table;
	    delete init_expr;
	    return;
      }


	/* Verify the "initial" statement, if present, to be sure that
	   it only assigns to the output and the output is
	   registered. Then save the initial value that I get. */
      verinum::V init = verinum::Vx;
      if (init_expr) {
	      // XXXX
	    assert(pins[0]->get_wire_type() == NetNet::REG);

	    PAssign*pa = dynamic_cast<PAssign*>(init_expr);
	    assert(pa);

	    const PEIdent*id = dynamic_cast<const PEIdent*>(pa->lval());
	    assert(id);

	      // XXXX
	      //assert(id->name() == pins[0]->name());

	    const PENumber*np = dynamic_cast<const PENumber*>(pa->rval());
	    assert(np);

	    init = np->value()[0];
      }

	// Put the primitive into the primitives table
      if (pform_primitives[name]) {
	    VLwarn("warning: UDP primitive already exists.");

      } else {
	    PUdp*udp = new PUdp(name, parms->size());
	    FILE_NAME(udp, loc);

	      // Detect sequential udp.
	    if (pins[0]->get_wire_type() == NetNet::REG)
		  udp->sequential = true;

	      // Make the port list for the UDP
	    for (unsigned idx = 0 ;  idx < pins.size() ;  idx += 1)
		  udp->ports[idx] = pins[idx]->basename();

	    process_udp_table(udp, table, loc);
	    udp->initial  = init;

	    pform_primitives[name] = udp;
      }


	/* Delete the excess tables and lists from the parser. */
      delete parms;
      delete decl;
      delete table;
      delete init_expr;
}

void pform_make_udp(const struct vlltype&loc, perm_string name,
		    bool synchronous_flag, perm_string out_name,
		    PExpr*init_expr, list<perm_string>*parms,
		    list<string>*table)
{

      std::vector<PWire*> pins(parms->size() + 1);

	/* Make the PWire for the output port. */
      pins[0] = new PWire(out_name,
			  synchronous_flag? NetNet::REG : NetNet::WIRE,
			  NetNet::POUTPUT);
      FILE_NAME(pins[0], loc);

	/* Make the PWire objects for the input ports. */
      { list<perm_string>::iterator cur;
        unsigned idx;
        for (cur = parms->begin(), idx = 1
		   ;  cur != parms->end()
		   ;  idx += 1, ++ cur) {
	      assert(idx < pins.size());
	      pins[idx] = new PWire(*cur, NetNet::WIRE,
				    NetNet::PINPUT);
	      FILE_NAME(pins[idx], loc);
	}
	assert(idx == pins.size());
      }

	/* Verify the initial expression, if present, to be sure that
	   it only assigns to the output and the output is
	   registered. Then save the initial value that I get. */
      verinum::V init = verinum::Vx;
      if (init_expr) {
	      // XXXX
	    assert(pins[0]->get_wire_type() == NetNet::REG);

	    PAssign*pa = dynamic_cast<PAssign*>(init_expr);
	    assert(pa);

	    const PEIdent*id = dynamic_cast<const PEIdent*>(pa->lval());
	    assert(id);

	      // XXXX
	      //assert(id->name() == pins[0]->name());

	    const PENumber*np = dynamic_cast<const PENumber*>(pa->rval());
	    assert(np);

	    init = np->value()[0];
      }

	// Put the primitive into the primitives table
      if (pform_primitives[name]) {
	    VLerror("error: UDP primitive already exists.");

      } else {
	    PUdp*udp = new PUdp(name, pins.size());
	    FILE_NAME(udp, loc);

	      // Detect sequential udp.
	    udp->sequential = synchronous_flag;

	      // Make the port list for the UDP
	    for (unsigned idx = 0 ;  idx < pins.size() ;  idx += 1)
		  udp->ports[idx] = pins[idx]->basename();

	    assert(udp);
	    assert(table);
	    process_udp_table(udp, table, loc);
	    udp->initial  = init;

	    pform_primitives[name] = udp;
      }

      delete parms;
      delete table;
      delete init_expr;
}

/*
 * This function attaches a range to a given name. The function is
 * only called by the parser within the scope of the net declaration,
 * and the name that I receive only has the tail component.
 */
static void pform_set_net_range(PWire *wire,
			        const vector_type_t *vec_type,
				PWSRType rt = SR_NET,
				std::list<named_pexpr_t>*attr = 0)
{
      pform_bind_attributes(wire->attributes, attr, true);

      if (!vec_type)
	    return;

      list<pform_range_t> *range = vec_type->pdims.get();
      if (range)
	    wire->set_range(*range, rt);
      wire->set_signed(vec_type->signed_flag);
}

/*
 * This is invoked to make a named event. This is the declaration of
 * the event, and not necessarily the use of it.
 */
static void pform_make_event(const struct vlltype&loc, perm_string name)
{
      PEvent*event = new PEvent(name);
      FILE_NAME(event, loc);

      add_local_symbol(lexical_scope, name, event);
      lexical_scope->events[name] = event;
}

void pform_make_events(const struct vlltype&loc, list<perm_string>*names)
{
      list<perm_string>::iterator cur;
      for (cur = names->begin() ;  cur != names->end() ; ++ cur ) {
	    perm_string txt = *cur;
	    pform_make_event(loc, txt);
      }

      delete names;
}

/*
 * pform_makegates is called when a list of gates (with the same type)
 * are ready to be instantiated. The function runs through the list of
 * gates and calls the pform_makegate function to make the individual gate.
 */
static void pform_makegate(PGBuiltin::Type type,
			   struct str_pair_t str,
			   list<PExpr*>* delay,
			   const lgate&info,
			   list<named_pexpr_t>*attr)
{
      if (info.parms_by_name) {
	    cerr << info.get_fileline() << ": error: Gates do not have port names."
		 << endl;
	    error_count += 1;
	    return;
      }

      if (info.parms) {
	    for (list<PExpr*>::iterator cur = info.parms->begin()
		       ; cur != info.parms->end() ; ++cur) {
		  pform_declare_implicit_nets(*cur);
	    }
      }

      perm_string dev_name = lex_strings.make(info.name);
      PGBuiltin*cur = new PGBuiltin(type, dev_name, info.parms, delay);
      cur->set_ranges(info.ranges);

	// The pform_makegates() that calls me will take care of
	// deleting the attr pointer, so tell the
	// pform_bind_attributes function to keep the attr object.
      pform_bind_attributes(cur->attributes, attr, true);

      cur->strength0(str.str0);
      cur->strength1(str.str1);
      cur->set_line(info);

      if (pform_cur_generate) {
	    if (dev_name != "") add_local_symbol(pform_cur_generate, dev_name, cur);
	    pform_cur_generate->add_gate(cur);
      } else {
	    if (dev_name != "") add_local_symbol(pform_cur_module.front(), dev_name, cur);
	    pform_cur_module.front()->add_gate(cur);
      }
}

void pform_makegates(const struct vlltype&loc,
		     PGBuiltin::Type type,
		     struct str_pair_t str,
		     list<PExpr*>*delay,
		     std::vector<lgate>*gates,
		     list<named_pexpr_t>*attr)
{
      assert(! pform_cur_module.empty());
      if (pform_cur_module.front()->program_block) {
	    cerr << loc << ": error: Gates and switches may not be instantiated in "
		 << "program blocks." << endl;
	    error_count += 1;
      }
      if (pform_cur_module.front()->is_interface) {
	    cerr << loc << ": error: Gates and switches may not be instantiated in "
		 << "interfaces." << endl;
	    error_count += 1;
      }

      for (unsigned idx = 0 ;  idx < gates->size() ;  idx += 1) {
	    pform_makegate(type, str, delay, (*gates)[idx], attr);
      }

      if (attr) delete attr;
      delete gates;
}

/*
 * A module is different from a gate in that there are different
 * constraints, and sometimes different syntax. The X_modgate
 * functions handle the instantiations of modules (and UDP objects) by
 * making PGModule objects.
 *
 * The first pform_make_modgate handles the case of a module
 * instantiated with ports passed by position. The "wires" is an
 * ordered array of port expressions.
 *
 * The second pform_make_modgate handles the case of a module
 * instantiated with ports passed by name. The "bind" argument is the
 * ports matched with names.
 */
static void pform_make_modgate(perm_string type,
			       perm_string name,
			       struct parmvalue_t*overrides,
			       list<PExpr*>*wires,
			       list<pform_range_t>*ranges,
			       const LineInfo&li,
			       std::list<named_pexpr_t>*attr)
{
      for (list<PExpr*>::iterator idx = wires->begin()
		 ; idx != wires->end() ; ++idx) {
	    pform_declare_implicit_nets(*idx);
      }

      PGModule*cur = new PGModule(type, name, wires);
      cur->set_line(li);
      cur->set_ranges(ranges);

      if (overrides && overrides->by_name) {
	    unsigned cnt = overrides->by_name->size();
	    named<PExpr*>*byname = new named<PExpr*>[cnt];

	    list<named_pexpr_t>::iterator by_name_cur = overrides->by_name->begin();
	    for (unsigned idx = 0 ;  idx < cnt ;  idx += 1, ++ by_name_cur) {
		  byname[idx].name = by_name_cur->name;
		  byname[idx].parm = by_name_cur->parm;
	    }

	    cur->set_parameters(byname, cnt);

      } else if (overrides && overrides->by_order) {
	    cur->set_parameters(overrides->by_order);
      }

      if (pform_cur_generate) {
	    if (name != "") add_local_symbol(pform_cur_generate, name, cur);
	    pform_cur_generate->add_gate(cur);
      } else {
	    if (name != "") add_local_symbol(pform_cur_module.front(), name, cur);
	    pform_cur_module.front()->add_gate(cur);
      }
      pform_bind_attributes(cur->attributes, attr);
}

static void pform_make_modgate(perm_string type,
			       perm_string name,
			       struct parmvalue_t*overrides,
			       list<named_pexpr_t>*bind,
			       list<pform_range_t>*ranges,
			       const LineInfo&li,
			       std::list<named_pexpr_t>*attr)
{
      unsigned npins = bind->size();
      named<PExpr*>*pins = new named<PExpr*>[npins];
      list<named_pexpr_t>::iterator bind_cur = bind->begin();
      for (unsigned idx = 0 ;  idx < npins ;  idx += 1,  ++bind_cur) {
	    pins[idx].name = bind_cur->name;
	    pins[idx].parm = bind_cur->parm;
            pform_declare_implicit_nets(bind_cur->parm);
      }

      PGModule*cur = new PGModule(type, name, pins, npins);
      cur->set_line(li);
      cur->set_ranges(ranges);

      if (overrides && overrides->by_name) {
	    unsigned cnt = overrides->by_name->size();
	    named<PExpr*>*byname = new named<PExpr*>[cnt];

	    list<named_pexpr_t>::iterator by_name_cur = overrides->by_name->begin();
	    for (unsigned idx = 0 ;  idx < cnt ;  idx += 1,  ++by_name_cur) {
		  byname[idx].name = by_name_cur->name;
		  byname[idx].parm = by_name_cur->parm;
	    }

	    cur->set_parameters(byname, cnt);

      } else if (overrides && overrides->by_order) {

	    cur->set_parameters(overrides->by_order);
      }

      if (pform_cur_generate) {
	    add_local_symbol(pform_cur_generate, name, cur);
	    pform_cur_generate->add_gate(cur);
      } else {
	    add_local_symbol(pform_cur_module.front(), name, cur);
	    pform_cur_module.front()->add_gate(cur);
      }
      pform_bind_attributes(cur->attributes, attr);
}

void pform_make_modgates(const struct vlltype&loc,
			 perm_string type,
			 struct parmvalue_t*overrides,
			 std::vector<lgate>*gates,
			 std::list<named_pexpr_t>*attr)
{
	// The grammer should not allow module gates to happen outside
	// an active module. But if really bad input errors combine in
	// an ugly way with error recovery, then catch this
	// implausible situation and return an error.
      if (pform_cur_module.empty()) {
	    cerr << loc << ": internal error: "
		 << "Module instantiations outside module scope are not possible."
		 << endl;
	    error_count += 1;
	    delete gates;
	    return;
      }
      assert(! pform_cur_module.empty());

	// Detect some more realistic errors.

      if (pform_cur_module.front()->program_block) {
	    cerr << loc << ": error: Module instantiations are not allowed in "
		 << "program blocks." << endl;
	    error_count += 1;
      }
      if (pform_cur_module.front()->is_interface) {
	    cerr << loc << ": error: Module instantiations are not allowed in "
		 << "interfaces." << endl;
	    error_count += 1;
      }

      for (unsigned idx = 0 ;  idx < gates->size() ;  idx += 1) {
	    lgate cur = (*gates)[idx];
	    perm_string cur_name = lex_strings.make(cur.name);

	    if (cur.parms_by_name) {
		  pform_make_modgate(type, cur_name, overrides,
				     cur.parms_by_name, cur.ranges,
				     cur, attr);

	    } else if (cur.parms) {

		    /* If there are no parameters, the parser will be
		       tricked into thinking it is one empty
		       parameter. This fixes that. */
		  if ((cur.parms->size() == 1) && (cur.parms->front() == 0)) {
			delete cur.parms;
			cur.parms = new list<PExpr*>;
		  }
		  pform_make_modgate(type, cur_name, overrides,
				     cur.parms, cur.ranges,
				     cur, attr);

	    } else {
		  list<PExpr*>*wires = new list<PExpr*>;
		  pform_make_modgate(type, cur_name, overrides,
				     wires, cur.ranges,
				     cur, attr);
	    }
      }

      delete gates;
}

static PGAssign* pform_make_pgassign(PExpr*lval, PExpr*rval,
			      list<PExpr*>*del,
			      struct str_pair_t str)
{
        /* Implicit declaration of nets on the LHS of a continuous
           assignment was introduced in IEEE1364-2001. */
      if (generation_flag != GN_VER1995)
            pform_declare_implicit_nets(lval);

      list<PExpr*>*wires = new list<PExpr*>;
      wires->push_back(lval);
      wires->push_back(rval);

      PGAssign*cur;

      if (del == 0)
	    cur = new PGAssign(wires);
      else
	    cur = new PGAssign(wires, del);

      cur->strength0(str.str0);
      cur->strength1(str.str1);

      if (pform_cur_generate)
	    pform_cur_generate->add_gate(cur);
      else
	    pform_cur_module.front()->add_gate(cur);

      return cur;
}

void pform_make_pgassign_list(const struct vlltype&loc,
			      list<PExpr*>*alist,
			      list<PExpr*>*del,
			      struct str_pair_t str)
{
      assert(alist->size() % 2 == 0);
      while (! alist->empty()) {
	    PExpr*lval = alist->front(); alist->pop_front();
	    PExpr*rval = alist->front(); alist->pop_front();
	    PGAssign*tmp = pform_make_pgassign(lval, rval, del, str);
	    FILE_NAME(tmp, loc);
      }
}

/*
 * This function makes the initial assignment to a variable as given
 * in the source. It handles the case where a variable is assigned
 * where it is declared, e.g.
 *
 *    reg foo = <expr>;
 *
 * In Verilog-2001 this is only supported at the module level, and is
 * equivalent to the combination of statements:
 *
 *    reg foo;
 *    initial foo = <expr>;
 *
 * In SystemVerilog, variable initializations are allowed in any scope.
 * For static variables, initializations are performed before the start
 * of simulation. For automatic variables, initializations are performed
 * each time the enclosing block is entered. Here we store the variable
 * assignments in the current scope, and later elaboration creates an
 * initialization block that will be executed at the appropriate time.
 *
 * This syntax is not part of the IEEE1364-1995 standard, but is
 * approved by OVI as enhancement BTF-B14.
 */
void pform_make_var_init(const struct vlltype&li,
			 perm_string name, PExpr*expr)
{
      if (! pform_at_module_level() && !gn_system_verilog()) {
	    VLerror(li, "error: Variable declaration assignments are only "
                        "allowed at the module level.");
	    delete expr;
	    return;
      }

      PEIdent*lval = new PEIdent(name);
      FILE_NAME(lval, li);
      PAssign*ass = new PAssign(lval, expr, !gn_system_verilog());
      FILE_NAME(ass, li);

      lexical_scope->var_inits.push_back(ass);
}

/*
 * This function makes a single signal (a wire, a reg, etc) as
 * requested by the parser. The name is unscoped, so I attach the
 * current scope to it (with the scoped_name function) and I try to
 * resolve it with an existing PWire in the scope.
 *
 * The wire might already exist because of an implicit declaration in
 * a module port, i.e.:
 *
 *     module foo (bar...
 *
 *         reg bar;
 *
 * The output (or other port direction indicator) may or may not have
 * been seen already, so I do not do any checking with it yet. But I
 * do check to see if the name has already been declared, as this
 * function is called for every declaration.
 */


static PWire* pform_get_or_make_wire(const struct vlltype&li, perm_string name,
				     NetNet::Type type, NetNet::PortType ptype,
				     PWSRType rt)
{
      PWire *cur = 0;

	// If this is not a full declaration check if there is already a signal
	// with the same name that can be extended.
      if (rt != SR_BOTH)
	    cur = pform_get_wire_in_scope(name);

	// If the wire already exists but isn't yet fully defined,
	// carry on adding details.
      if (rt == SR_NET && cur && !cur->is_net()) {
	      // At the moment there can only be one location for the PWire, if
	      // there is both a port and signal declaration use the location of
	      // the signal.
	    FILE_NAME(cur, li);
	    cur->set_net(type);
	    return cur;
      }

      if (rt == SR_PORT && cur && !cur->is_port()) {
	    cur->set_port(ptype);
	    return cur;
      }

	// If the wire already exists and is fully defined, this
	// must be a redeclaration. Start again with a new wire.
	// The error will be reported when we add the new wire
	// to the scope. Do not delete the old wire - it will
	// remain in the local symbol map.

      cur = new PWire(name, type, ptype, rt);
      FILE_NAME(cur, li);

      pform_put_wire_in_scope(name, cur);

      return cur;
}


/*
 * This function is used by the parser when I have port definition of
 * the form like this:
 *
 *     input wire signed [7:0] nm;
 *
 * The port_type, type, signed_flag and range are known all at once,
 * so we can create the PWire object all at once instead of piecemeal
 * as is done for the old method.
 */
void pform_module_define_port(const struct vlltype&li,
			      perm_string name,
			      NetNet::PortType port_kind,
			      NetNet::Type type,
			      data_type_t*vtype,
			      list<pform_range_t>*urange,
			      list<named_pexpr_t>*attr,
			      bool keep_attr)
{
      pform_check_net_data_type(li, type, vtype);

      PWire *cur = pform_get_or_make_wire(li, name, type, port_kind, SR_BOTH);

      pform_set_net_range(cur, dynamic_cast<vector_type_t*> (vtype), SR_BOTH);

      if (vtype)
	    cur->set_data_type(vtype);

      if (urange) {
	    cur->set_unpacked_idx(*urange);
	    delete urange;
      }

      pform_bind_attributes(cur->attributes, attr, keep_attr);
}

void pform_module_define_port(const struct vlltype&li,
			      list<pform_port_t>*ports,
			      NetNet::PortType port_kind,
			      NetNet::Type type,
			      data_type_t*vtype,
			      list<named_pexpr_t>*attr)
{
      for (list<pform_port_t>::iterator cur = ports->begin()
		 ; cur != ports->end() ; ++ cur ) {

	    data_type_t*use_type = vtype;

	    pform_module_define_port(li, cur->name, port_kind, type, use_type,
				     cur->udims, attr, true);

	    if (cur->expr)
		  pform_make_var_init(li, cur->name, cur->expr);
      }

      delete ports;
      delete attr;
}

/*
 * this is the basic form of pform_makewire. This takes a single simple
 * name, port type, net type, data type, and attributes, and creates
 * the variable/net. Other forms of pform_makewire ultimately call
 * this one to create the wire and stash it.
 */
PWire *pform_makewire(const vlltype&li, perm_string name, NetNet::Type type,
		      std::list<pform_range_t> *indices)
{
      PWire*cur = pform_get_or_make_wire(li, name, type, NetNet::NOT_A_PORT,
				         SR_NET);
      assert(cur);

      if (indices && !indices->empty())
	    cur->set_unpacked_idx(*indices);

      return cur;
}

void pform_makewire(const struct vlltype&li,
		    std::list<PExpr*>*delay,
		    str_pair_t str,
		    std::list<decl_assignment_t*>*assign_list,
		    NetNet::Type type,
		    data_type_t*data_type,
		    list<named_pexpr_t>*attr)
{
      if (is_compilation_unit(lexical_scope) && !gn_system_verilog()) {
	    VLerror(li, "error: Variable declarations must be contained within a module.");
	    return;
      }

      std::vector<PWire*> *wires = new std::vector<PWire*>;

      for (list<decl_assignment_t*>::iterator cur = assign_list->begin()
		 ; cur != assign_list->end() ; ++ cur) {
	    decl_assignment_t* curp = *cur;
	    PWire *wire = pform_makewire(li, curp->name, type, &curp->index);
	    wires->push_back(wire);
      }

      pform_set_data_type(li, data_type, wires, type, attr);

      while (! assign_list->empty()) {
	    decl_assignment_t*first = assign_list->front();
	    assign_list->pop_front();
            if (PExpr*expr = first->expr.release()) {
                  if (type == NetNet::REG || type == NetNet::IMPLICIT_REG) {
                        pform_make_var_init(li, first->name, expr);
                  } else {
		        PEIdent*lval = new PEIdent(first->name);
		        FILE_NAME(lval, li);
		        PGAssign*ass = pform_make_pgassign(lval, expr, delay, str);
		        FILE_NAME(ass, li);
                  }
            }
	    delete first;
      }
}

/*
 * This function is called by the parser to create task ports. The
 * resulting wire (which should be a register) is put into a list to
 * be packed into the task parameter list.
 *
 * It is possible that the wire (er, register) was already created,
 * but we know that if the name matches it is a part of the current
 * task, so in that case I just assign direction to it.
 *
 * The following example demonstrates some of the issues:
 *
 *   task foo;
 *      input a;
 *      reg a, b;
 *      input b;
 *      [...]
 *   endtask
 *
 * This function is called when the parser matches the "input a" and
 * the "input b" statements. For ``a'', this function is called before
 * the wire is declared as a register, so I create the foo.a
 * wire. For ``b'', I will find that there is already a foo.b and I
 * just set the port direction. In either case, the ``reg a, b''
 * statement is caught by the block_item non-terminal and processed
 * there.
 *
 * Ports are implicitly type reg, because it must be possible for the
 * port to act as an l-value in a procedural assignment. It is obvious
 * for output and inout ports that the type is reg, because the task
 * only contains behavior (no structure) to a procedural assignment is
 * the *only* way to affect the output. It is less obvious for input
 * ports, but in practice an input port receives its value as if by a
 * procedural assignment from the calling behavior.
 *
 * This function also handles the input ports of function
 * definitions. Input ports to function definitions have the same
 * constraints as those of tasks, so this works fine. Functions have
 * no output or inout ports.
 */
vector<pform_tf_port_t>*pform_make_task_ports(const struct vlltype&loc,
				      NetNet::PortType pt,
				      data_type_t*vtype,
				      list<pform_port_t>*ports,
				      bool allow_implicit)
{
      assert(pt != NetNet::PIMPLICIT && pt != NetNet::NOT_A_PORT);
      assert(ports);

      vector<pform_tf_port_t>*res = new vector<pform_tf_port_t>(0);
      PWSRType rt = SR_BOTH;

      // If this is a non-ansi port declaration and the type is an implicit type
      // this is only a port declaration.
      vector_type_t*vec_type = dynamic_cast<vector_type_t*>(vtype);
      if (allow_implicit && (!vtype || (vec_type && vec_type->implicit_flag)))
	    rt = SR_PORT;

      for (list<pform_port_t>::iterator cur = ports->begin();
	   cur != ports->end(); ++cur) {
	    perm_string &name = cur->name;

	    PWire*curw = pform_get_or_make_wire(loc, name, NetNet::IMPLICIT_REG,
						pt, rt);
	    if (rt == SR_BOTH)
		  curw->set_data_type(vtype);

	    pform_set_net_range(curw, vec_type, rt);

	    if (cur->udims) {
		  if (pform_requires_sv(loc, "Task/function port with unpacked dimensions"))
			curw->set_unpacked_idx(*cur->udims);
	    }

	    res->push_back(pform_tf_port_t(curw));
      }

      delete ports;
      return res;
}

/*
 * The parser calls this in the rule that matches increment/decrement
 * statements. The rule that does the matching creates a PEUnary with
 * all the information we need, but here we convert that expression to
 * a compressed assignment statement.
 */
PAssign* pform_compressed_assign_from_inc_dec(const struct vlltype&loc, PExpr*exp)
{
      PEUnary*expu = dynamic_cast<PEUnary*> (exp);
      ivl_assert(*exp, expu != 0);

      char use_op = 0;
      switch (expu->get_op()) {
	  case 'i':
	  case 'I':
	    use_op = '+';
	    break;
	  case 'd':
	  case 'D':
	    use_op = '-';
	    break;
	  default:
	    ivl_assert(*exp, 0);
	    break;
      }

      PExpr*lval = expu->get_expr();
      PExpr*rval = new PENumber(new verinum((uint64_t)1, 1));
      FILE_NAME(rval, loc);

      PAssign*tmp = new PAssign(lval, use_op, rval);
      FILE_NAME(tmp, loc);

      delete exp;
      return tmp;
}

PExpr* pform_genvar_inc_dec(const struct vlltype&loc, const char*name, bool inc_flag)
{
      pform_requires_sv(loc, "Increment/decrement operator");

      PExpr*lval = new PEIdent(lex_strings.make(name));
      PExpr*rval = new PENumber(new verinum(1));
      FILE_NAME(lval, loc);
      FILE_NAME(rval, loc);

      PEBinary*tmp = new PEBinary(inc_flag ? '+' : '-', lval, rval);
      FILE_NAME(tmp, loc);

      return tmp;
}

PExpr* pform_genvar_compressed(const struct vlltype &loc, const char *name,
			       char op, PExpr *rval)
{
      pform_requires_sv(loc, "Compressed assignment operator");

      PExpr *lval = new PEIdent(lex_strings.make(name));
      FILE_NAME(lval, loc);

      PExpr *expr;
      switch (op) {
	  case 'l':
	  case 'r':
	  case 'R':
	    expr = new PEBShift(op, lval, rval);
	    break;
	  default:
	    expr = new PEBinary(op, lval, rval);
	    break;
      }
      FILE_NAME(expr, loc);

      return expr;
}

void pform_set_attrib(perm_string name, perm_string key, char*value)
{
      if (PWire*cur = lexical_scope->wires_find(name)) {
	    cur->attributes[key] = new PEString(value);

      } else if (PGate*curg = pform_cur_module.front()->get_gate(name)) {
	    curg->attributes[key] = new PEString(value);

      } else {
	    delete[] value;
	    VLerror("error: Unable to match name for setting attribute.");

      }
}

/*
 * Set the attribute of a TYPE. This is different from an object in
 * that this applies to every instantiation of the given type.
 */
void pform_set_type_attrib(perm_string name, const string&key,
			   char*value)
{
      map<perm_string,PUdp*>::const_iterator udp = pform_primitives.find(name);
      if (udp == pform_primitives.end()) {
	    VLerror("error: Type name is not (yet) defined.");
	    delete[] value;
	    return;
      }

      (*udp).second ->attributes[key] = new PEString(value);
}

LexicalScope::range_t* pform_parameter_value_range(bool exclude_flag,
					     bool low_open, PExpr*low_expr,
					     bool hig_open, PExpr*hig_expr)
{
	// Detect +-inf and make the the *_open flags false to force
	// the range interpretation as inf.
      if (low_expr == 0) low_open = false;
      if (hig_expr == 0) hig_open = false;

      LexicalScope::range_t*tmp = new LexicalScope::range_t;
      tmp->exclude_flag = exclude_flag;
      tmp->low_open_flag = low_open;
      tmp->low_expr = low_expr;
      tmp->high_open_flag = hig_open;
      tmp->high_expr = hig_expr;
      tmp->next = 0;
      return tmp;
}

static void pform_set_type_parameter(const struct vlltype&loc, perm_string name,
				     LexicalScope::range_t*value_range)
{
      pform_requires_sv(loc, "Type parameter");

      if (value_range)
	    VLerror(loc, "error: Type parameter must not have value range.");

      type_parameter_t *type = new type_parameter_t(name);
      pform_set_typedef(loc, name, type, 0);
}

void pform_set_parameter(const struct vlltype&loc,
			 perm_string name, bool is_local, bool is_type,
			 data_type_t*data_type, PExpr*expr,
			 LexicalScope::range_t*value_range)
{
      LexicalScope*scope = lexical_scope;
      if (is_compilation_unit(scope) && !gn_system_verilog()) {
	    VLerror(loc, "error: %s declarations must be contained within a module.",
		         is_local ? "localparam" : "parameter");
	    return;
      }

      if (expr == 0) {
	    if (is_local) {
		  VLerror(loc, "error: localparam must have a value.");
	    } else if (!pform_in_parameter_port_list) {
		  VLerror(loc, "error: parameter declared outside parameter "
			        "port list must have a default value.");
	    } else {
		  pform_requires_sv(loc, "parameter without default value");
	    }
      }

      bool overridable = !is_local;

      if (scope == pform_cur_generate && !is_local) {
	    if (!gn_system_verilog()) {
		  VLerror(loc, "parameter declarations are not permitted in generate blocks");
		  return;
	    }
	    // SystemVerilog allows `parameter` in generate blocks, but it has
	    // the same semantics as `localparam` in that scope.
	    overridable = false;
      }

      bool in_module = dynamic_cast<Module*>(scope) &&
		       scope == pform_cur_module.front();

      if (!pform_in_parameter_port_list && in_module &&
          scope->has_parameter_port_list)
	    overridable = false;

      if (pform_in_class())
	    overridable = false;

      Module::param_expr_t*parm = new Module::param_expr_t();
      FILE_NAME(parm, loc);

      if (is_type)
	    pform_set_type_parameter(loc, name, value_range);
      else
	    add_local_symbol(scope, name, parm);

      parm->expr = expr;
      parm->data_type = data_type;
      parm->range = value_range;
      parm->local_flag = is_local;
      parm->overridable = overridable;
      parm->type_flag = is_type;

      scope->parameters[name] = parm;

      // Only a module keeps the position of the parameter.
      if (overridable && in_module)
	    pform_cur_module.front()->param_names.push_back(name);
}

void pform_set_specparam(const struct vlltype&loc, perm_string name,
			 list<pform_range_t>*range, PExpr*expr)
{
      assert(! pform_cur_module.empty());
      Module*scope = pform_cur_module.front();
      if (scope != lexical_scope) {
	    delete range;
	    delete expr;
	    return;
      }

      assert(expr);
      Module::param_expr_t*parm = new Module::param_expr_t();
      FILE_NAME(parm, loc);

      add_local_symbol(scope, name, parm);
      pform_cur_module.front()->specparams[name] = parm;

      parm->expr = expr;
      parm->range = 0;

      if (range) {
	    assert(range->size() == 1);
	    parm->data_type = new vector_type_t(IVL_VT_LOGIC, false, range);
	    parm->range = 0;
      }
}

void pform_set_defparam(const pform_name_t&name, PExpr*expr)
{
      assert(expr);
      if (pform_cur_generate)
            pform_cur_generate->defparms.push_back(make_pair(name,expr));
      else
            pform_cur_module.front()->defparms.push_back(make_pair(name,expr));
}

void pform_make_let(const struct vlltype&loc,
                    perm_string name,
                    list<PLet::let_port*>*ports,
                    PExpr*expr)
{
      LexicalScope*scope =  pform_peek_scope();

      cerr << loc.get_fileline() << ": sorry: let declarations ("
           << name << ") are not currently supported." << endl;
      error_count += 1;

      PLet*res = new PLet(name, scope, ports, expr);
      FILE_NAME(res, loc);

/*
      cerr << "Found: ";
      res->dump(cerr, 0);
*/

      delete res;
      delete ports;
      delete expr;
}

PLet::let_port_t* pform_make_let_port(data_type_t*data_type,
                                      perm_string name,
                                      list<pform_range_t>*range,
                                      PExpr*def)
{
      PLet::let_port_t*res = new PLet::let_port_t;

      res->type_ = data_type;
      res->name_ = name;
      res->range_ = range;
      res->def_ = def;

      return res;
}

/*
 * Specify paths.
 */
extern PSpecPath* pform_make_specify_path(const struct vlltype&li,
					  list<perm_string>*src, char pol,
					  bool full_flag, list<perm_string>*dst)
{
      PSpecPath*path = new PSpecPath(src->size(), dst->size(), pol, full_flag);
      FILE_NAME(path, li);

      unsigned idx;
      list<perm_string>::const_iterator cur;

      idx = 0;
      for (idx = 0, cur = src->begin() ;  cur != src->end() ;  ++ idx, ++ cur) {
	    path->src[idx] = *cur;
      }
      assert(idx == path->src.size());
      delete src;

      for (idx = 0, cur = dst->begin() ;  cur != dst->end() ;  ++ idx, ++ cur) {
	    path->dst[idx] = *cur;
      }
      assert(idx == path->dst.size());
      delete dst;

      return path;
}

extern PSpecPath*pform_make_specify_edge_path(const struct vlltype&li,
					 int edge_flag, /*posedge==true */
					 list<perm_string>*src, char pol,
					 bool full_flag, list<perm_string>*dst,
					 PExpr*data_source_expression)
{
      PSpecPath*tmp = pform_make_specify_path(li, src, pol, full_flag, dst);
      tmp->edge = edge_flag;
      tmp->data_source_expression = data_source_expression;
      return tmp;
}

extern PSpecPath* pform_assign_path_delay(PSpecPath*path, list<PExpr*>*del)
{
      if (path == 0)
	    return 0;

      assert(path->delays.empty());

      path->delays.resize(del->size());
      for (unsigned idx = 0 ;  idx < path->delays.size() ;  idx += 1) {
	    path->delays[idx] = del->front();
	    del->pop_front();
      }

      delete del;

      return path;
}


extern void pform_module_specify_path(PSpecPath*obj)
{
      if (obj == 0)
	    return;
      pform_cur_module.front()->specify_paths.push_back(obj);
}


void pform_set_port_type(const struct vlltype&li,
			 list<pform_port_t>*ports,
			 NetNet::PortType pt,
			 data_type_t*dt,
			 list<named_pexpr_t>*attr)
{
      assert(pt != NetNet::PIMPLICIT && pt != NetNet::NOT_A_PORT);

      vector_type_t *vt = dynamic_cast<vector_type_t*> (dt);

      bool have_init_expr = false;
      for (list<pform_port_t>::iterator cur = ports->begin()
		 ; cur != ports->end() ; ++ cur ) {

	    PWire *wire = pform_get_or_make_wire(li, cur->name,
						 NetNet::IMPLICIT, pt,
						 SR_PORT);
	    pform_set_net_range(wire, vt, SR_PORT, attr);

	    if (cur->udims) {
		  cerr << li << ": warning: "
		       << "Array dimensions in incomplete port declarations "
		       << "are currently ignored." << endl;
		  cerr << li << ":        : "
		       << "The dimensions specified in the net or variable "
		       << "declaration will be used." << endl;
		  delete cur->udims;
	    }
	    if (cur->expr) {
		  have_init_expr = true;
		  delete cur->expr;
	    }
      }
      if (have_init_expr) {
	    cerr << li << ": error: "
		 << "Incomplete port declarations cannot be initialized."
		 << endl;
	    error_count += 1;
      }

      delete ports;
      delete dt;
      delete attr;
}

/*
 * This function detects the derived class for the given type and
 * dispatches the type to the proper subtype function.
 */
void pform_set_data_type(const struct vlltype&li, data_type_t*data_type,
			 std::vector<PWire*> *wires, NetNet::Type net_type,
			 list<named_pexpr_t>*attr)
{
      if (data_type == 0) {
	    VLerror(li, "internal error: data_type==0.");
	    assert(0);
      }

      vector_type_t*vec_type = dynamic_cast<vector_type_t*> (data_type);

      for (std::vector<PWire*>::iterator it= wires->begin();
	   it != wires->end() ; ++it) {
	    PWire *wire = *it;

	    pform_set_net_range(wire, vec_type);

	    // If these fail there is a bug somewhere else. pform_set_data_type()
	    // is only ever called on a fresh wire that already exists.
	    bool rc = wire->set_wire_type(net_type);
	    ivl_assert(li, rc);

	    wire->set_data_type(data_type);

	    pform_bind_attributes(wire->attributes, attr, true);
      }

      delete wires;
}

vector<PWire*>* pform_make_udp_input_ports(list<perm_string>*names)
{
      vector<PWire*>*out = new vector<PWire*>(names->size());

      unsigned idx = 0;
      for (list<perm_string>::iterator cur = names->begin()
		 ; cur != names->end() ; ++ cur ) {
	    perm_string txt = *cur;
	    PWire*pp = new PWire(txt,
				 NetNet::IMPLICIT,
				 NetNet::PINPUT);
	    (*out)[idx] = pp;
	    idx += 1;
      }

      delete names;
      return out;
}

PProcess* pform_make_behavior(ivl_process_type_t type, Statement*st,
			      list<named_pexpr_t>*attr)
{
	// Add an implicit @* around the statement for the always_comb and
	// always_latch statements.
      if ((type == IVL_PR_ALWAYS_COMB) || (type == IVL_PR_ALWAYS_LATCH)) {
	    PEventStatement *tmp = new PEventStatement(true);
	    tmp->set_line(*st);
	    tmp->set_statement(st);
	    st = tmp;
      }

      PProcess*pp = new PProcess(type, st);

	// If we are in a part of the code where the meta-comment
	// synthesis translate_off is in effect, then implicitly add
	// the ivl_synthesis_off attribute to any behavioral code that
	// we run into.
      if (pform_mc_translate_flag == false) {
	    if (attr == 0) attr = new list<named_pexpr_t>;
	    named_pexpr_t tmp;
	    tmp.name = perm_string::literal("ivl_synthesis_off");
	    tmp.parm = 0;
	    attr->push_back(tmp);
      }

      pform_bind_attributes(pp->attributes, attr);

      pform_put_behavior_in_scope(pp);

      ivl_assert(*st, ! pform_cur_module.empty());
      if (pform_cur_module.front()->program_block &&
          ((type == IVL_PR_ALWAYS) || (type == IVL_PR_ALWAYS_COMB) ||
           (type == IVL_PR_ALWAYS_FF) || (type == IVL_PR_ALWAYS_LATCH))) {
	    cerr << st->get_fileline() << ": error: Always statements are not allowed"
		 << " in program blocks." << endl;
	    error_count += 1;
      }

      return pp;
}

void pform_start_modport_item(const struct vlltype&loc, const char*name)
{
      Module*scope = pform_cur_module.front();
      ivl_assert(loc, scope && scope->is_interface);
      ivl_assert(loc, pform_cur_modport == 0);

      perm_string use_name = lex_strings.make(name);
      pform_cur_modport = new PModport(use_name);
      FILE_NAME(pform_cur_modport, loc);

      add_local_symbol(scope, use_name, pform_cur_modport);
      scope->modports[use_name] = pform_cur_modport;

      delete[] name;
}

void pform_end_modport_item(const struct vlltype&loc)
{
      ivl_assert(loc, pform_cur_modport);
      pform_cur_modport = 0;
}

void pform_add_modport_port(const struct vlltype&loc,
                            NetNet::PortType port_type,
                            perm_string name, PExpr*expr)
{
      ivl_assert(loc, pform_cur_modport);

      if (pform_cur_modport->simple_ports.find(name)
	  != pform_cur_modport->simple_ports.end()) {
	    cerr << loc << ": error: duplicate declaration of port '"
		 << name << "' in modport list '"
		 << pform_cur_modport->name() << "'." << endl;
	    error_count += 1;
      }
      pform_cur_modport->simple_ports[name] = make_pair(port_type, expr);
}

bool pform_requires_sv(const struct vlltype&loc, const char *feature)
{
      if (gn_system_verilog())
	    return true;

      VLerror(loc, "error: %s requires SystemVerilog.", feature);

      return false;
}

void pform_check_net_data_type(const struct vlltype&loc, NetNet::Type net_type,
			       const data_type_t *data_type)
{
      // For SystemVerilog the type is checked during elaboration since due to
      // forward typedefs and type parameters the actual type might not be known
      // yet.
      if (gn_system_verilog())
	    return;

      switch (net_type) {
      case NetNet::REG:
      case NetNet::IMPLICIT_REG:
	    return;
      default:
	    break;
      }

      if (!data_type)
	    return;

      const vector_type_t*vec_type = dynamic_cast<const vector_type_t*>(data_type);
      if (vec_type && vec_type->implicit_flag)
	    return;

      const real_type_t*rtype = dynamic_cast<const real_type_t*>(data_type);
      if (rtype && rtype->type_code() == real_type_t::REAL)
	    return;

      pform_requires_sv(loc, "Net data type");
}

FILE*vl_input = 0;
extern void reset_lexor();

int pform_parse(const char*path)
{
      vl_file = path;
      if (strcmp(path, "-") == 0) {
	    vl_input = stdin;
      } else if (ivlpp_string) {
	    char*cmdline = (char*)malloc(strlen(ivlpp_string) +
					        strlen(path) + 4);
	    strcpy(cmdline, ivlpp_string);
	    strcat(cmdline, " \"");
	    strcat(cmdline, path);
	    strcat(cmdline, "\"");

	    if (verbose_flag)
		  cerr << "Executing: " << cmdline << endl<< flush;

	    vl_input = popen(cmdline, "r");
	    if (vl_input == 0) {
		  cerr << "Unable to preprocess " << path << "." << endl;
		  return 1;
	    }

	    if (verbose_flag)
		  cerr << "...parsing output from preprocessor..." << endl << flush;

	    free(cmdline);
      } else {
	    vl_input = fopen(path, "r");
	    if (vl_input == 0) {
		  cerr << "Unable to open " << path << "." << endl;
		  return 1;
	    }
      }

      if (pform_units.empty() || separate_compilation) {
	    char unit_name[20];
	    static unsigned nunits = 0;
	    if (separate_compilation)
		  snprintf(unit_name, sizeof(unit_name)-1, "$unit#%u", ++nunits);
	    else
		  snprintf(unit_name, sizeof(unit_name)-1, "$unit");

	    PPackage*unit = new PPackage(lex_strings.make(unit_name), 0);
	    unit->default_lifetime = LexicalScope::STATIC;
	    unit->set_file(filename_strings.make(path));
	    unit->set_lineno(1);
	    pform_units.push_back(unit);

            pform_cur_module.clear();
            pform_cur_generate = 0;
            pform_cur_modport = 0;

	    pform_set_timescale(def_ts_units, def_ts_prec, 0, 0);

	    allow_timeunit_decl = true;
	    allow_timeprec_decl = true;

	    lexical_scope = unit;
      }
      reset_lexor();
      error_count = 0;
      warn_count = 0;
      int rc = VLparse();

      if (vl_input != stdin) {
	    if (ivlpp_string)
		  pclose(vl_input);
	    else
		  fclose(vl_input);
      }

      if (rc) {
	    cerr << "I give up." << endl;
	    error_count += 1;
      }

      destroy_lexor();
      return error_count;
}