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

/*----------------------------------------------------------------------*/
/* The verilog input is limited to "structural verilog", that is,	*/
/* verilog code that only defines inputs, outputs, local nodes (via the	*/
/* "wire" statement), and instanced modules.  All modules are read down	*/
/* to the point where either a module (1) does not conform to the	*/
/* requirements above, or (2) has no module definition, in which case	*/
/* it is treated as a "black box" subcircuit and therefore becomes a	*/
/* low-level device.  Because in verilog syntax all instances of a	*/
/* module repeat both the module pin names and the local connections,	*/
/* placeholders can be built without the need to redefine pins later,	*/
/* as must be done for formats like SPICE that don't declare pin names	*/
/* in an instance call.							*/
/*----------------------------------------------------------------------*/

/*----------------------------------------------------------------------*/
/* Note that use of 1'b0 or 1'b1 and similar variants is prohibited;	*/
/* the structural netlist should either declare VSS and/or VDD as	*/
/* inputs, or use tie-high and tie-low standard cells.			*/
/*----------------------------------------------------------------------*/

/*----------------------------------------------------------------------*/
/* Most verilog syntax has been captured below.  Still to do:  Handle	*/
/* wires that are created on the fly using {...} notation, including	*/
/* the {n{...}} concatenation method.  Currently this syntax is only	*/
/* handled in nets connected to instance pins.				*/
/*----------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <sys/types.h>
#include <pwd.h>

#include "hash.h"
#include "readverilog.h"

/*------------------------------------------------------*/
/* Global variables					*/
/*------------------------------------------------------*/

struct filestack *OpenFiles = NULL;
int linesize = 0;	/* Amount of memory allocated for line */
int vlinenum = 0;
char *nexttok;
char *linetok;
char *line = NULL;	/* The line read in */
FILE *infile = NULL;

struct hashtable verilogparams;
struct hashtable verilogdefs;
struct hashtable verilogvectors;

char dictinit = FALSE;

/*------------------------------------------------------*/
/* Structure for stacking nested `if[n]def		*/
/*------------------------------------------------------*/

struct ifstack {
    int invert;
    char *kl;
    struct ifstack *next;
};

struct ifstack *condstack = NULL;

/*------------------------------------------------------*/
/* Stack handling (push and pop)			*/
/*------------------------------------------------------*/

void PushStack(struct cellrec *cell, struct cellstack **top)
{
   struct cellstack *newstack;

   newstack = (struct cellstack *)calloc(1, sizeof(struct cellstack));
   newstack->cell = cell;
   newstack->next = *top;
   *top = newstack;
}

/*------------------------------------------------------*/

struct cellrec *PopStack(struct cellstack **top)
{
   struct cellstack *stackptr;
   struct cellrec *cellptr;

   stackptr = *top;
   cellptr = stackptr->cell;
   if (!stackptr) return NULL;
   *top = stackptr->next;
   free(stackptr);

   return cellptr;
}

/*----------------------------------------------------------------------*/
/* Routine that can be called to pre-install a definition into the	*/
/* verilogdefs hash table.						*/
/*----------------------------------------------------------------------*/

void VerilogDefine(char *key, char *value)
{
    if (dictinit == FALSE) {
	InitializeHashTable(&verilogdefs, TINYHASHSIZE);
	dictinit = TRUE;
    }
    HashPtrInstall(key, strdup(value), &verilogdefs);
}

/*----------------------------------------------------------------------*/
/* Function similar to strtok() for token parsing.  The difference is   */
/* that it takes two sets of delimiters.  The first is whitespace       */
/* delimiters, which separate tokens.  The second is functional         */
/* delimiters, which separate tokens and have additional meaning, such  */
/* as parentheses, commas, semicolons, etc.  The parser needs to know   */
/* when such tokens occur in the string, so they are returned as        */
/* individual tokens.                                                   */
/*                                                                      */
/* Definition of delim2:  String of single delimiter characters.  The   */
/* special character "X" (which is never a delimiter in practice) is    */
/* used to separate single-character delimiters from two-character      */
/* delimiters (this presumably could be further extended as needed).    */
/* so ",;()" would be a valid delimiter set, but to include C-style     */
/* comments and verilog-style parameter lists, one would need           */
/* ",;()X/**///#(".                                                     */
/*----------------------------------------------------------------------*/

char *strdtok(char *pstring, char *delim1, char *delim2)
{
    static char *stoken = NULL;
    static char *sstring = NULL;
    char *s, *s2;
    char first = FALSE;
    int twofer;

    if (pstring != NULL) {
	/* Allocate enough memory to hold the string;  tokens will be put here */
	if (sstring != NULL) free(sstring);
	sstring = (char *)malloc(strlen(pstring) + 1);
	stoken = pstring;
	first = TRUE;
    }

    /* Skip over "delim1" delimiters at the string beginning */
    for (; *stoken; stoken++) {
        for (s2 = delim1; *s2; s2++)
            if (*stoken == *s2)
                break;
        if (*s2 == '\0') break;
    }

    if (*stoken == '\0') return NULL;   /* Finished parsing */

    /* "stoken" is now set.  Now find the end of the current token */
    /* Check string from position stoken.  If a character in "delim2" is found, */
    /* save the character in "lastdelim", null the byte at that position, and   */
    /* return the token.  If a character in "delim1" is found, do the same but  */
    /* continue checking characters as long as there are contiguous "delim1"    */
    /* characters.  If the series ends in a character from "delim2", then treat */
    /* as for "delim2" above.  If not, then set "lastdelim" to a null byte and  */
    /* return the token.                                                        */

    s = stoken;

    /* Special verilog rule:  If a name begins with '\', then all characters	*/
    /* are a valid part of the name until a space character is reached.	  The	*/
    /* space character becomes part of the verilog name.  The remainder of the	*/
    /* name is parsed according to the rules of "delim2".			*/

    if (*s == '\\') {
	while (*s != '\0') {
	    if (*s == ' ') {
		s++;
		break;
	    }
	    s++;
	}
    }

    for (; *s; s++) {
	twofer = TRUE;
	for (s2 = delim2; s2 && *s2; s2++) {
	    if (*s2 == 'X') {
		twofer = FALSE;
		continue;
	    }
	    if (twofer) {
		if ((*s == *s2) && (*(s + 1) == *(s2 + 1))) {
		    if (s == stoken) {
			strncpy(sstring, stoken, 2);
			*(sstring + 2) = '\0';
			stoken = s + 2;
		    }
		    else {
			strncpy(sstring, stoken, (int)(s - stoken));
			*(sstring + (s - stoken)) = '\0';
			stoken = s;
		    }
		    return sstring;
		}
		s2++;
		if (*s2 == '\0') break;
	    }
	    else if (*s == *s2) {
		if (s == stoken) {
		    strncpy(sstring, stoken, 1);
		    *(sstring + 1) = '\0';
		    stoken = s + 1;
		}
		else {
		    strncpy(sstring, stoken, (int)(s - stoken));
		    *(sstring + (s - stoken)) = '\0';
		    stoken = s;
		}
		return sstring;
	    }
	}
	for (s2 = delim1; *s2; s2++) {
	    if (*s == *s2) {
		strncpy(sstring, stoken, (int)(s - stoken));
		*(sstring + (s - stoken)) = '\0';
		stoken = s;
		return sstring;
	    }
	}
    }
    strcpy(sstring, stoken);    /* Just copy to the end */
    stoken = s;
    return sstring;
}

/*----------------------------------------------------------------------*/
/* File opening, closing, and stack handling				*/
/* Return 0 on success, -1 on error.					*/
/*----------------------------------------------------------------------*/

int OpenParseFile(char *name)
{
    /* Push filestack */

    FILE *locfile = NULL;
    struct filestack *newfile;

    locfile = fopen(name, "r");
    vlinenum = 0;
    /* reset the token scanner */
    nexttok = NULL;

    if (locfile != NULL) {
	if (infile != NULL) {
	    newfile = (struct filestack *)malloc(sizeof(struct filestack));
	    newfile->file = infile;
	    newfile->next = OpenFiles;
	    OpenFiles = newfile;
	}
	infile = locfile;
    }
    return (locfile == NULL) ? -1 : 0;
}

/*----------------------------------------------------------------------*/

int EndParseFile(void)
{
    return feof(infile);
}

/*----------------------------------------------------------------------*/

int CloseParseFile(void)
{
    struct filestack *lastfile;
    int rval;
    rval = fclose(infile);
    infile = (FILE *)NULL;

    /* Pop filestack if not empty */
    lastfile = OpenFiles;
    if (lastfile != NULL) {
	OpenFiles = lastfile->next;
	infile = lastfile->file;
	free(lastfile);
    }
    return rval;
}

/*----------------------------------------------------------------------*/

void InputParseError(FILE *f)
{
    char *ch;

    fprintf(f, "line number %d = '", vlinenum);
    for (ch = line; *ch != '\0'; ch++) {
	if (isprint(*ch)) fprintf(f, "%c", *ch);
	else if (*ch != '\n') fprintf(f, "<<%d>>", (int)(*ch));
    }
    fprintf(f, "'\n");
}

/*----------------------------------------------------------------------*/
/* Tokenizer routines							*/
/*----------------------------------------------------------------------*/

#define WHITESPACE_DELIMITER " \t\n\r"

/*----------------------------------------------------------------------*/
/* TrimQuoted() ---                                                     */
/* Remove spaces from inside single- or double-quoted strings.          */
/* Exclude bit values (e.g., "1'b0")					*/
/*----------------------------------------------------------------------*/

void TrimQuoted(char *line)
{
    char *qstart, *qend, *lptr;
    int slen;
    int changed;

    /* Single-quoted entries */
    changed = TRUE;
    lptr = line;
    while (changed)
    {
	changed = FALSE;
	qstart = strchr(lptr, '\'');
	if (qstart && (qstart > lptr)) {
	    if (isdigit(*(qstart - 1))) {
		lptr = qstart + 1;
		changed = TRUE;
		continue;
	    }
	}
	if (qstart)
	{
	    qend = strrchr(qstart + 1, '\'');
	    if (qend && (qend > qstart)) {
		slen = strlen(lptr);
		for (lptr = qstart + 1; lptr < qend; lptr++) {
		    if (*lptr == ' ') {
			memmove(lptr, lptr + 1, slen);
			qend--;
			changed = TRUE;
		    }
		}
		lptr++;
	    }
	}
    }

    /* Double-quoted entries */
    changed = TRUE;
    lptr = line;
    while (changed)
    {
	changed = FALSE;
	qstart = strchr(lptr, '\"');
	if (qstart)
	{
	    qend = strchr(qstart + 1, '\"');
	    if (qend && (qend > qstart)) {
		slen = strlen(lptr);
		for (lptr = qstart + 1; lptr < qend; lptr++) {
		    if (*lptr == ' ') {
			memmove(lptr, lptr + 1, slen);
			qend--;
			changed = TRUE;
		    }
		}
		lptr++;
	    }
	}
    }
}

/*----------------------------------------------------------------------*/
/* GetNextLineNoNewline()                                               */
/*                                                                      */
/* Fetch the next line, and grab the first token from the next line.    */
/* If there is no next token (next line is empty, and ends with a       */
/* newline), then place NULL in nexttok.                                */
/*                                                                      */
/*----------------------------------------------------------------------*/

int GetNextLineNoNewline(char *delimiter)
{
    char *newbuf;
    int testc;
    int nested = 0;
    char *s, *t, *w, e, *kl;
    int len, dlen, vlen, addin;
    unsigned char found;

    if (feof(infile)) return -1;

    while (1) {		/* May loop indefinitely in an `if[n]def conditional */

	// This is more reliable than feof() ...
	testc = getc(infile);
	if (testc == -1) return -1;
	ungetc(testc, infile);

	if (linesize == 0) {
	    /* Allocate memory for line */
	    linesize = 500;
	    line = (char *)malloc(linesize);
	    linetok = (char *)malloc(linesize);
	}
	fgets(line, linesize, infile);
	while (strlen(line) == linesize - 1) {
	    newbuf = (char *)malloc(linesize + 500);
	    strcpy(newbuf, line);
	    free(line);
	    line = newbuf;
	    fgets(line + linesize - 1, 501, infile);
	    linesize += 500;
	    free(linetok);
	    linetok = (char *)malloc(linesize * sizeof(char));
	}

	/* Check for substitutions.  Make sure linetok is large enough 	*/
	/* to hold the entire line after substitutions.			*/

	found = FALSE;
	addin = 0;
	for (s = line; *s != '\0'; s++) {
	    if (*s == '`') {
		w = s + 1;
		while (isalnum(*w)) w++;
		e = *w;
		*w = '\0';
		kl = (char *)HashLookup(s + 1, &verilogdefs);
		if (kl != NULL) {
		    dlen = strlen(s);
		    vlen = strlen(kl);
		    addin += vlen - dlen + 1;
		    found = TRUE;
		}
		*w = e;
	    }
	}
	if (found) {
	    len = strlen(line);
	    if (len + addin > linesize) {
		while (len + addin > linesize) linesize += 500;
		free(linetok);
		linetok = (char *)malloc(linesize);
	    }
	}

	/* Make definition substitutions */

	t = linetok;
	for (s = line; *s != '\0'; s++) {
	    if (*s == '`') {
		w = s + 1;
		while (isalnum(*w)) w++;
		e = *w;
		*w = '\0';
		kl = (char *)HashLookup(s + 1, &verilogdefs);
		if (kl != NULL) {
		    strcpy(t, kl);
		    t += strlen(t);
		    s = w - 1;
		}
		else *t++ = *s;
		*w = e;
	    }
	    else *t++ = *s;
	}
	*t = '\0';

	TrimQuoted(linetok);
	vlinenum++;

	nexttok = strdtok(linetok, WHITESPACE_DELIMITER, delimiter);
	if (nexttok == NULL) return 0;

	/* Handle `ifdef, `ifndef, `elsif, `else, and `endif */

	/* If currently skipping through a section, handle conditionals differently */
	if (condstack) {
	    if (((condstack->invert == 0) && (condstack->kl == NULL))
			|| ((condstack->invert == 1) && (condstack->kl != NULL))) {
		if (match(nexttok, "`ifdef") || match(nexttok, "`ifndef")) {
		    nested++;
		    continue;
		}
		else if (nested > 0) {
		    if (match(nexttok, "`endif")) nested--;
		    continue;
		}
		else if (nexttok[0] != '`') continue;
	    }
	}

	/* Handle conditionals (not being skipped over) */

	if (match(nexttok, "`endif")) {
	    if (condstack == NULL) {
		fprintf(stderr, "Error:  `endif without corresponding `if[n]def\n");
	    }
	    else {
		struct ifstack *iftop = condstack;
		condstack = condstack->next;
		free(iftop);
	    }
	}

	/* `if[n]def may be nested. */

	else if (match(nexttok, "`ifdef") || match(nexttok, "`ifndef") ||
			match(nexttok, "`elsif") || match(nexttok, "`else")) {

	    /* Every `ifdef or `ifndef increases condstack by 1 */
	    if (nexttok[1] == 'i') {
		struct ifstack *newif = (struct ifstack *)malloc(sizeof(struct ifstack));
		newif->next = condstack;
		condstack = newif;
	    }
	    if (condstack == NULL) {
		fprintf(stderr, "Error:  %s without `if[n]def\n", nexttok);
		break;
	    }
	    else {
		if (match(nexttok, "`else")) {
		    /* Invert the sense of the if[n]def scope */
		    condstack->invert = (condstack->invert == 1) ? 0 : 1;
		}
		else if (match(nexttok, "`elsif")) {
		    nexttok = strdtok(NULL, WHITESPACE_DELIMITER, delimiter);
		    if (nexttok == NULL) {
			fprintf(stderr, "Error:  `elsif with no conditional.\n");
			return 0;
		    }
		    /* Keep the same scope but redefine the parameter */
		    condstack->invert = 0;
		    condstack->kl = (char *)HashLookup(nexttok, &verilogdefs);
		}
		else {
		    condstack->invert = (nexttok[3] == 'n') ? 1 : 0;
		    nexttok = strdtok(NULL, WHITESPACE_DELIMITER, delimiter);
		    if (nexttok == NULL) {
			fprintf(stderr, "Error:  %s with no conditional.\n", nexttok);
			return 0;
		    }
		    condstack->kl = (char *)HashLookup(nexttok, &verilogdefs);
		}
	    }
	}
	else if (condstack) {
	    if (((condstack->invert == 0) && (condstack->kl == NULL))
			|| ((condstack->invert == 1) && (condstack->kl != NULL)))
		continue;
	    else
		break;
	}
	else
	    break;
    }
    return 0;
}

/*----------------------------------------------------------------------*/
/* Get the next line of input from file "infile", and find the first    */
/* valid token.                                                         */
/*----------------------------------------------------------------------*/

void GetNextLine(char *delimiter)
{
    do {
	if (GetNextLineNoNewline(delimiter) == -1) return;
    } while (nexttok == NULL);
}

/*----------------------------------------------------------------------*/
/* skip to the end of the current line                                  */
/*----------------------------------------------------------------------*/

void SkipNewLine(char *delimiter)
{
    while (nexttok != NULL)
	nexttok = strdtok(NULL, WHITESPACE_DELIMITER, delimiter);
}

/*----------------------------------------------------------------------*/
/* if nexttok is already NULL, force scanner to read new line           */
/*----------------------------------------------------------------------*/

void SkipTok(char *delimiter)
{
    if (nexttok != NULL &&
		(nexttok = strdtok(NULL, WHITESPACE_DELIMITER, delimiter)))
	return;
    GetNextLine(delimiter);
}

/*----------------------------------------------------------------------*/
/* like SkipTok, but will not fetch a new line when the buffer is empty */
/* must be preceeded by at least one call to SkipTok()                  */
/*----------------------------------------------------------------------*/

void SkipTokNoNewline(char *delimiter)
{
    nexttok = strdtok(NULL, WHITESPACE_DELIMITER, delimiter);
}

/*----------------------------------------------------------------------*/
/* Skip to the next token, ignoring any C-style comments.               */
/*----------------------------------------------------------------------*/

void SkipTokComments(char *delimiter)
{
    SkipTok(delimiter);
    while (nexttok) {
	if (!strcmp(nexttok, "//")) {
	    SkipNewLine(delimiter);
	    SkipTok(delimiter);
	}
	else if (!strcmp(nexttok, "/*")) {
	    while (nexttok && strcmp(nexttok, "*/"))
		SkipTok(delimiter);
	    if (nexttok) SkipTok(delimiter);
	}
	else if (!strcmp(nexttok, "(*")) {
	    while (nexttok && strcmp(nexttok, "*)"))
		SkipTok(delimiter);
	    if (nexttok) SkipTok(delimiter);
	}
	else break;
    }
}

/*----------------------------------------------------------------------*/
/* Free a bus structure in the hash table during cleanup		*/
/*----------------------------------------------------------------------*/

int freenet (struct hashlist *p)
{
    struct netrec *wb;

    wb = (struct netrec *)(p->ptr);
    free(wb);
    return 1;
}

/*----------------------------------------------------------------------*/
/* Create a new net (or bus) structure					*/
/*----------------------------------------------------------------------*/

struct netrec *NewNet()
{
    struct netrec *wb;

    wb = (struct netrec *)calloc(1, sizeof(struct netrec));
    if (wb == NULL) fprintf(stderr, "NewNet: Core allocation error\n");
    return (wb);
}

/*----------------------------------------------------------------------*/
/* BusHashLookup --							*/
/* Run HashLookup() on a string, first removing any bus delimiters.	*/
/*----------------------------------------------------------------------*/

void *BusHashLookup(char *s, struct hashtable *table)
{
    void *rval;
    char *dptr = NULL;
    char *sptr = s;

    if (*sptr == '\\') {
	sptr = strchr(s, ' ');
	if (sptr == NULL) sptr = s;
    }
    if ((dptr = strchr(sptr, '[')) != NULL) *dptr = '\0';

    rval = HashLookup(s, table);
    if (dptr) *dptr = '[';
    return rval;
}

/*----------------------------------------------------------------------*/
/* BusHashPtrInstall --							*/
/* Run HashPtrInstall() on a string, first removing any bus delimiters.	*/
/*----------------------------------------------------------------------*/

struct hashlist *BusHashPtrInstall(char *name, void *ptr,
                                struct hashtable *table)
{
    struct hashlist *rval;
    char *dptr = NULL;
    char *sptr = name;

    if (*sptr == '\\') {
	sptr = strchr(name, ' ');
	if (sptr == NULL) sptr = name;
    }
    if ((dptr = strchr(sptr, '[')) != NULL) *dptr = '\0';

    rval = HashPtrInstall(name, ptr, table);
    if (dptr) *dptr = '[';
    return rval;
}

/*------------------------------------------------------------------------------*/
/* Get bus indexes from the notation name[a:b].  If there is only "name"	*/
/* then look up the name in the bus hash list and return the index bounds.	*/
/* Return 0 on success, 1 on syntax error, and -1 if signal is not a bus.	*/
/*										*/
/* Note that this routine relies on the delimiter characters including		*/
/* "[", ":", and "]" when calling NextTok.					*/
/*------------------------------------------------------------------------------*/

int GetBusTok(struct netrec *wb, struct hashtable *nets)
{
    int result, start, end;
    char *kl;

    if (wb == NULL) return 0;
    else {
        wb->start = -1;
        wb->end = -1;
    }

    if (!strcmp(nexttok, "[")) {
	SkipTokComments(VLOG_DELIMITERS);

	// Check for parameter names and substitute values if found.
	result = sscanf(nexttok, "%d", &start);
	if (result != 1) {
	    char *aptr = NULL;
	    char addin;

	    // Check for "+/-(n)" at the end of a parameter name
	    aptr = strrchr(nexttok, '+');
	    if (aptr == NULL) aptr = strrchr(nexttok, '-');
	    if (aptr != NULL) {
		addin = *aptr;
		*aptr = '\0';
	    }

	    // Is name in the parameter list?
	    kl = (char *)HashLookup(nexttok, &verilogparams);
	    if (kl == NULL) {
		fprintf(stdout, "Array value %s is not a number or a "
				"parameter (line %d).\n", nexttok, vlinenum);
		return 1;
	    }
	    else {
		result = sscanf(kl, "%d", &start);
		if (result != 1) {
		    fprintf(stdout, "Parameter %s has value %s that cannot be parsed"
				" as an integer (line %d).\n", nexttok, kl, vlinenum);
		    return 1;
		}
	    }
	    if (aptr != NULL) {
		int addval;
		*aptr = addin;
		if (sscanf(aptr + 1, "%d", &addval) != 1) {
		    fprintf(stdout, "Unable to parse parameter increment \"%s\" "
			    "(line %d).\n", aptr, vlinenum);
		    return 1;
		}
		start += (addin == '+') ? addval : -addval;
	    }
	}

	SkipTokComments(VLOG_DELIMITERS);
	if (!strcmp(nexttok, "]")) {
	    result = 1;
	    end = start;	// Single bit
	}
	else if (strcmp(nexttok, ":")) {
	    fprintf(stdout, "Badly formed array notation:  Expected colon, "
			"found %s (line %d)\n", nexttok, vlinenum);
	    return 1;
	}
	else {
	    SkipTokComments(VLOG_DELIMITERS);

	    // Check for parameter names and substitute values if found.
	    result = sscanf(nexttok, "%d", &end);
	    if (result != 1) {
		char *aptr = NULL;
		char addin;

		// Check for "+/-(n)" at the end of a parameter name
		aptr = strrchr(nexttok, '+');
		if (aptr == NULL) aptr = strrchr(nexttok, '-');
		if (aptr != NULL) {
		    addin = *aptr;
		    *aptr = '\0';
		}

		// Is name in the parameter list?
	        kl = (char *)HashLookup(nexttok, &verilogparams);
		if (kl == NULL) {
		    fprintf(stdout, "Array value %s is not a number or a "
				"parameter (line %d).\n", nexttok, vlinenum);
		    return 1;
		}
		else {
		    result = sscanf(kl, "%d", &end);
		    if (result != 1) {
		        fprintf(stdout, "Parameter %s has value %s that cannot"
				" be parsed as an integer (line %d).\n",
				nexttok, kl, vlinenum);
			return 1;
		    }
		}
		if (aptr != NULL) {
		    int addval;
		    *aptr = addin;
		    if (sscanf(aptr + 1, "%d", &addval) != 1) {
			fprintf(stdout, "Unable to parse parameter increment \"%s\" "
				"(line %d).\n", aptr, vlinenum);
			return 1;
		    }
		    end += (addin == '+') ? addval : -addval;
		}
	    }
	}
	wb->start = start;
	wb->end = end;

	while (strcmp(nexttok, "]")) {
	    SkipTokComments(VLOG_DELIMITERS);
	    if (nexttok == NULL) {
		fprintf(stdout, "End of file reached while reading array bounds.\n");
		return 1;
	    }
	    else if (!strcmp(nexttok, ";")) {
		// Better than reading to end-of-file, give up on end-of-statement
		fprintf(stdout, "End of statement reached while reading "
				"array bounds (line %d).\n", vlinenum);
		return 1;
	    }
	}
	/* Move token forward to bus name */
	SkipTokComments(VLOG_DELIMITERS);
    }
    else if (nets) {
	struct netrec *hbus;
	hbus = (struct netrec *)BusHashLookup(nexttok, nets);
	if (hbus != NULL) {
	    wb->start = hbus->start;
	    wb->end = hbus->end;
	}
	else
	    return -1;
    }
    return 0;
}

/*----------------------------------------------------------------------*/
/* GetBus() is similar to GetBusTok() (see above), but it parses from	*/
/* a string instead of the input tokenizer.				*/
/*----------------------------------------------------------------------*/

int GetBus(char *astr, struct netrec *wb, struct hashtable *nets)
{
    char *colonptr, *brackstart, *brackend, *sstr;
    int result, start, end;

    if (wb == NULL) return 0;
    else {
        wb->start = -1;
        wb->end = -1;
    }
    sstr = astr;

    // Skip to the end of verilog names bounded by '\' and ' '
    if (*sstr == '\\')
	while (*sstr && *sstr != ' ') sstr++;

    brackstart = strchr(sstr, '[');
    if (brackstart != NULL) {
	brackend = strchr(sstr, ']');
	if (brackend == NULL) {
	    fprintf(stdout, "Badly formed array notation \"%s\" (line %d)\n", astr,
			vlinenum);
	    return 1;
	}
	*brackend = '\0';
	colonptr = strchr(sstr, ':');
	if (colonptr) *colonptr = '\0';
	result = sscanf(brackstart + 1, "%d", &start);
	if (colonptr) *colonptr = ':';
	if (result != 1) {
	    fprintf(stdout, "Badly formed array notation \"%s\" (line %d)\n", astr,
			vlinenum);
	    *brackend = ']';
	    return 1;
	}
	if (colonptr)
	    result = sscanf(colonptr + 1, "%d", &end);
	else {
	    result = 1;
	    end = start;        // Single bit
	}
	*brackend = ']';
	if (result != 1) {
	    fprintf(stdout, "Badly formed array notation \"%s\" (line %d)\n", astr,
			vlinenum);
	    return 1;
	}
	wb->start = start;
	wb->end = end;
    }
    else if (nets) {
	struct netrec *hbus;
	hbus = (struct netrec *)BusHashLookup(astr, nets);
	if (hbus != NULL) {
	    wb->start = hbus->start;
	    wb->end = hbus->end;
	}
	else
	    return -1;
    }
    return 0;
}

/*------------------------------------------------------*/
/* Add net to cell database				*/
/*------------------------------------------------------*/

struct netrec *Net(struct cellrec *cell, char *netname)
{
    struct netrec *newnet;

    newnet = NewNet();
    newnet->start = -1;
    newnet->end = -1;

    /* Install net in net hash */
    BusHashPtrInstall(netname, newnet, &cell->nets);

    return newnet;
}

/*------------------------------------------------------*/
/* Add port to instance record				*/
/*------------------------------------------------------*/

struct portrec *InstPort(struct instance *inst, char *portname, char *netname)
{
    struct portrec *portsrch, *newport;

    newport = (struct portrec *)malloc(sizeof(struct portrec));
    newport->name = strdup(portname);
    newport->direction = PORT_NONE;
    if (netname)
	newport->net = strdup(netname);
    else
	newport->net = NULL;
    newport->next = NULL; 

    /* Go to end of the port list */
    if (inst->portlist == NULL) {
	inst->portlist = newport;
    }
    else {
	for (portsrch = inst->portlist; portsrch->next; portsrch = portsrch->next);
 	portsrch->next = newport;
    }
    return newport;
}

/*------------------------------------------------------*/
/* Add port to cell database				*/
/*------------------------------------------------------*/

void Port(struct cellrec *cell, char *portname, struct netrec *net, int port_type)
{
    struct portrec *portsrch, *newport;
    struct netrec *newnet;

    newport = (struct portrec *)malloc(sizeof(struct portrec));
    if (portname)
	newport->name = strdup(portname);
    else
	newport->name = NULL;
    newport->direction = port_type;
    newport->net = NULL;
    newport->next = NULL; 

    /* Go to end of the port list */
    if (cell->portlist == NULL) {
	cell->portlist = newport;
    }
    else {
	for (portsrch = cell->portlist; portsrch->next; portsrch = portsrch->next);
 	portsrch->next = newport;
    }

    /* Register the port name as a net in the cell */
    if (portname)
    {
	newnet = Net(cell, portname);
	if (net) {
	    newnet->start = net->start;
	    newnet->end = net->end;
	}
    }
}

/*------------------------------------------------------*/
/* Create a new cell					*/
/*------------------------------------------------------*/

struct cellrec *Cell(char *cellname)
{
    struct cellrec *new_cell;

    new_cell = (struct cellrec *)malloc(sizeof(struct cellrec));
    new_cell->name = strdup(cellname);
    new_cell->portlist = NULL;
    new_cell->instlist = NULL;
    new_cell->lastinst = NULL;

    InitializeHashTable(&new_cell->nets, LARGEHASHSIZE);
    InitializeHashTable(&new_cell->propdict, TINYHASHSIZE);

    return new_cell;
}

/*------------------------------------------------------*/
/* Add instance to cell database			*/
/*------------------------------------------------------*/

struct instance *Instance(struct cellrec *cell, char *cellname, int prepend)
{
    struct instance *newinst, *instsrch;

    /* Create new instance record */
    newinst = (struct instance *)malloc(sizeof(struct instance));

    newinst->instname = NULL;
    newinst->cellname = strdup(cellname);
    newinst->portlist = NULL;
    newinst->next = NULL;

    InitializeHashTable(&newinst->propdict, TINYHASHSIZE);
	
    if (cell->instlist == NULL) {
	cell->instlist = newinst;
    }
    else {
	if (prepend == TRUE) {
	    newinst->next = cell->instlist;
	    cell->instlist = newinst;
	}
	else {
	    instsrch = (cell->lastinst != NULL) ?
			cell->lastinst : cell->instlist;

	    /* Go to end of the instance list */
	    for (; instsrch->next; instsrch = instsrch->next);
		
	    cell->lastinst = instsrch;
 	    instsrch->next = newinst;
	}
    }
    return newinst;
}

struct instance *AppendInstance(struct cellrec *cell, char *cellname)
{
    return Instance(cell, cellname, FALSE);
}

struct instance *PrependInstance(struct cellrec *cell, char *cellname)
{
    return Instance(cell, cellname, TRUE);
}

/*------------------------------------------------------*/
/* Read a verilog structural netlist			*/
/*------------------------------------------------------*/

void ReadVerilogFile(char *fname, struct cellstack **CellStackPtr,
			int blackbox)
{
    int i;
    int warnings = 0, hasports, inlined_decls = 0, localcount = 1;
    int port_type = PORT_NONE;
    char in_module, in_param;
    char *eqptr;
    char pkey[256];

    struct cellrec *top = NULL;

    in_module = (char)0;
    in_param = (char)0;
  
    while (!EndParseFile()) {

	SkipTokComments(VLOG_DELIMITERS); /* get the next token */

	/* Diagnostic */
	/* if (nexttok) fprintf(stdout, "Token is \"%s\"\n", nexttok); */

	if ((EndParseFile()) && (nexttok == NULL)) break;
	else if (nexttok == NULL)
	    break;

	/* Ignore end-of-statement markers */
	else if (!strcmp(nexttok, ";"))
	    continue;

	/* Ignore primitive definitions */
	else if (!strcmp(nexttok, "primitive")) {
	    while (1) {
		SkipNewLine(VLOG_DELIMITERS);
		SkipTokComments(VLOG_DELIMITERS);
		if (EndParseFile()) break;
		if (!strcmp(nexttok, "endprimitive")) {
		    in_module = 0;
		    break;
		}
	    }
	}

	else if (!strcmp(nexttok, "module")) {
	    struct netrec wb;

	    SkipTokNoNewline(VLOG_DELIMITERS);
	    if (nexttok == NULL) {
		fprintf(stderr, "Badly formed \"module\" line (line %d)\n", vlinenum);
		goto skip_endmodule;
	    }

	    if (in_module == (char)1) {
		fprintf(stderr, "Missing \"endmodule\" statement on "
				"subcircuit (line %d).\n", vlinenum);
		InputParseError(stderr);
	    }
	    in_module = (char)1;
	    hasports = (char)0;
	    inlined_decls = (char)0;

	    /* If there is an existing module, then push it */
	    if (top != NULL) PushStack(top, CellStackPtr);

	    /* Create new cell */
	    top = Cell(nexttok);

	    /* Need to support both types of I/O lists:  Those	*/
	    /* that declare names only in the module list and	*/
	    /* follow with input/output and vector size		*/
	    /* declarations as individual statements in the	*/
	    /* module definition, and those which declare	*/
	    /* everything inside the pin list.			*/

            SkipTokComments(VLOG_DELIMITERS);

	    // Check for parameters within #( ... ) 

	    if (!strcmp(nexttok, "#(")) {
		SkipTokComments(VLOG_DELIMITERS);
		in_param = (char)1;
	    }
	    else if (!strcmp(nexttok, "(")) {
		SkipTokComments(VLOG_DELIMITERS);
	    }

	    wb.start = wb.end = -1;
            while ((nexttok != NULL) && strcmp(nexttok, ";")) {
		if (in_param) {
		    if (!strcmp(nexttok, ")")) {
			in_param = (char)0;
			SkipTokComments(VLOG_DELIMITERS);
			if (strcmp(nexttok, "(")) {
			    fprintf(stderr, "Badly formed module block parameter"
						" list (line %d).\n", vlinenum);
			    goto skip_endmodule;
			}
		    }
		    else if (!strcmp(nexttok, "=")) {

			// The parameter value is the next token.
			SkipTokComments(VLOG_DELIMITERS); /* get the next token */
			HashPtrInstall(pkey, strdup(nexttok), &top->propdict);
		    }
		    else {
			/* Assume this is a keyword and save it */
			strcpy(pkey, nexttok);
		    }
		}
		else if (strcmp(nexttok, ",")) {
		    if (!strcmp(nexttok, ")")) break;
		    // Ignore input, output, and inout keywords, and handle buses.

		    if (inlined_decls == (char)0) {
			if (!strcmp(nexttok, "input") || !strcmp(nexttok, "output")
				|| !strcmp(nexttok, "inout"))
			    inlined_decls = (char)1;
		    }

		    if (inlined_decls == (char)1) {
			if (!strcmp(nexttok, "input"))
			    port_type = PORT_INPUT;
			else if (!strcmp(nexttok, "output"))
			    port_type = PORT_OUTPUT;
			else if (!strcmp(nexttok, "inout"))
			    port_type = PORT_INOUT;
			else if (strcmp(nexttok, "real") && strcmp(nexttok, "logic")
					&& strcmp(nexttok, "wire")
					&& strcmp(nexttok, "integer")) {
			    if (!strcmp(nexttok, "[")) {
				if (GetBusTok(&wb, &top->nets) != 0) {
				    // Didn't parse as a bus, so wing it
				    Port(top, nexttok, NULL, port_type);
				}
				else
				    Port(top, nexttok, &wb, port_type);
			    }
			    else
				Port(top, nexttok, NULL, port_type);

			    hasports = 1;
			}
		    }
		}
		SkipTokComments(VLOG_DELIMITERS);
		if (nexttok == NULL) break;
	    }
	    if (inlined_decls == 1) {
		if (hasports == 0)
		    // If the cell defines no ports, then create a proxy
		    Port(top, (char *)NULL, NULL, PORT_NONE);

		/* In the blackbox case, don't read the cell contents */
		if (blackbox) goto skip_endmodule;
	    }
	}
	else if (!strcmp(nexttok, "input") || !strcmp(nexttok, "output")
			|| !strcmp(nexttok, "inout")) {
	    struct netrec wb;

	    if (!strcmp(nexttok, "input")) port_type = PORT_INPUT;
	    else if (!strcmp(nexttok, "output")) port_type = PORT_OUTPUT;
	    else if (!strcmp(nexttok, "inout")) port_type = PORT_INOUT;
	    else port_type = PORT_NONE;
 
	    // Parsing of ports as statements not in the module pin list.
	    wb.start = wb.end = -1;
	    while (1) {
		SkipTokComments(VLOG_DELIMITERS);
		if (EndParseFile()) break;

		if (!strcmp(nexttok, ";")) {
		    // End of statement
		    break;
		}
		else if (!strcmp(nexttok, "[")) {
		    if (GetBusTok(&wb, &top->nets) != 0) {
			// Didn't parse as a bus, so wing it
			Port(top, nexttok, NULL, port_type);
		    }
		    else
			Port(top, nexttok, &wb, port_type);
		}
		else if (strcmp(nexttok, ",")) {
		    /* Comma-separated list;  use same bus limits */
		    Port(top, nexttok, &wb, port_type);
		}
		hasports = 1;
	    }
	}
	else if (!strcmp(nexttok, "endmodule")) {

	    if (in_module == (char)0) {
		fprintf(stderr, "\"endmodule\" occurred outside of a "
				"module (line %d)!\n", vlinenum);
	        InputParseError(stderr);
	    }
	    in_module = (char)0;
	    SkipNewLine(VLOG_DELIMITERS);
	}
	else if (!strcmp(nexttok, "`include")) {
	    char *iname, *iptr, *quotptr, *pathend, *userpath = NULL;

	    SkipTokNoNewline(VLOG_DELIMITERS);
	    if (nexttok == NULL) continue;	/* Ignore if no filename */

	    // Any file included in another Verilog file needs to be
	    // interpreted relative to the path of the parent Verilog file,
	    // unless it's an absolute pathname.

	    pathend = strrchr(fname, '/');
	    iptr = nexttok;
	    while (*iptr == '\'' || *iptr == '\"') iptr++;
	    if ((pathend != NULL) && (*iptr != '/') && (*iptr != '~')) {
		*pathend = '\0';
		iname = (char *)malloc(strlen(fname) + strlen(iptr) + 2);
		sprintf(iname, "%s/%s", fname, iptr);
		*pathend = '/';
	    }
	    else if ((*iptr == '~') && (*(iptr + 1) == '/')) {
		/* For ~/<path>, substitute tilde from $HOME */
		userpath = getenv("HOME");
		iname = (char *)malloc(strlen(userpath) + strlen(iptr));
		sprintf(iname, "%s%s", userpath, iptr + 1);
	    }
	    else if (*iptr == '~') {
		/* For ~<user>/<path>, substitute tilde from getpwnam() */
		struct passwd *passwd;
		char *pathstart;
		pathstart = strchr(iptr, '/');
		if (pathstart) *pathstart = '\0';
		passwd = getpwnam(iptr + 1);
		if (passwd != NULL) {
		    userpath = passwd->pw_dir;
		    if (pathstart) {
			*pathstart = '/';
			iname = (char *)malloc(strlen(userpath) + strlen(pathstart) + 1);
			sprintf(iname, "%s%s", userpath, pathstart);
		    }
		    else {
			/* Almost certainly an error, but make the substitution anyway */
			iname = strdup(userpath);
		    }
		}
		else {
		    /* Probably an error, but copy the filename verbatim */
		    iname = strdup(iptr);
		}
	    }
	    else
		iname = strdup(iptr);

	    // Eliminate any single or double quotes around the filename
	    iptr = iname;
	    quotptr = iptr;
	    while (*quotptr != '\'' && *quotptr != '\"' && 
			*quotptr != '\0' && *quotptr != '\n') quotptr++;
	    if (*quotptr == '\'' || *quotptr == '\"') *quotptr = '\0';
	
	    IncludeVerilog(iptr, CellStackPtr, blackbox);
	    free(iname);
	    SkipNewLine(VLOG_DELIMITERS);
	}
	else if (!strcmp(nexttok, "`define")) {
	    char *key;

	    /* Parse for definitions used in expressions.  Save	*/
	    /* definitions in the "verilogdefs" hash table.	*/

	    SkipTokNoNewline(VLOG_DELIMITERS);
	    if ((nexttok == NULL) || (nexttok[0] == '\0')) break;

	    key = strdup(nexttok);

	    SkipTokNoNewline(VLOG_DELIMITERS);
	    if ((nexttok == NULL) || (nexttok[0] == '\0'))
		/* Let "`define X" be equivalent to "`define X 1". */
		HashPtrInstall(key, strdup("1"), &verilogdefs);
	    else	 
		HashPtrInstall(key, strdup(nexttok), &verilogdefs);
	}
	else if (!strcmp(nexttok, "parameter") || !strcmp(nexttok, "localparam")) {
	    char *paramkey = NULL;
	    char *paramval = NULL;

	    // Pick up key = value pairs and store in current cell.  Look only
	    // at the keyword before "=".  Then set the definition as everything
	    // remaining in the line, excluding comments, until the end-of-statement

	    while (nexttok != NULL)
	    {
		/* Parse for parameters used in expressions.  Save	*/
		/* parameters in the "verilogparams" hash table.	*/

		SkipTok(VLOG_DELIMITERS);
		if ((nexttok == NULL) || (nexttok[0] == '\0')) break;
		if (!strcmp(nexttok, "=")) {
		    /* Pick up remainder of statement */
		    while (nexttok != NULL) {
			SkipTokNoNewline("X///**/X;,");
			if (nexttok == NULL) break;
			if (!strcmp(nexttok, ";") || !strcmp(nexttok, ",")) break;
			if (paramval == NULL) paramval = strdup(nexttok);
			else {
			    char *paramlast;
			    /* Append nexttok to paramval */
			    paramlast = paramval;
			    paramval = (char *)malloc(strlen(paramlast) +
					strlen(nexttok) + 2);
			    sprintf(paramval, "%s %s", paramlast, nexttok);
			    free(paramlast);
			}
		    }
		    HashPtrInstall(paramkey, paramval, &verilogparams);
		    free(paramval);
		    paramval = NULL;
		    if ((nexttok == NULL) || !strcmp(nexttok, ";")) break;
		}
		else {
		    if (paramkey != NULL) free(paramkey);
		    paramkey = strdup(nexttok);
		}
	    }
	    if (paramval != NULL) free(paramval);
	    if (paramkey != NULL) free(paramkey);
	}
	else if (!strcmp(nexttok, "real") || !strcmp(nexttok, "integer")) {
	    fprintf(stdout, "Ignoring '%s' in module '%s' (line %d)\n",
		    nexttok, top->name, vlinenum);
	    while (strcmp(nexttok, ";")) SkipTok("X///**/X,;");
	    continue;
	}
	else if (!strcmp(nexttok, "wire") ||
		 !strcmp(nexttok, "assign")) {	/* wire = node */
	    struct netrec wb, *nb;
	    char *eptr, *wirename;
	    char is_assignment = FALSE;
	    char is_lhs_bundle = FALSE, is_rhs_bundle = FALSE;
	    char is_wire = (strcmp(nexttok, "wire")) ? FALSE : TRUE;

	    // Several allowed uses of "assign":
	    // "assign a = b" joins two nets.
	    // "assign a = {b, c, ...}" creates a signal bundle from components.
	    // "assign {a, b ...} = {c, d, ...}" creates a bundle from another bundle.
	    // "assign" using any boolean arithmetic is not structural verilog.

	    SkipTokNoNewline(VLOG_DELIMITERS);
	    if (!strcmp(nexttok, "real"))
		SkipTokNoNewline(VLOG_DELIMITERS);
	    else if (!strcmp(nexttok, "logic"))
		SkipTokNoNewline(VLOG_DELIMITERS);

	    while (nexttok != NULL) {
		if (!strcmp(nexttok, "=")) {
		    is_assignment = TRUE;
		}
		else if (!strcmp(nexttok, "{")) {
		    /* To be done:  allow nested bundles */
		    if (is_assignment == FALSE) is_lhs_bundle = TRUE;
		    else is_rhs_bundle = TRUE;
		}
		else if (!strcmp(nexttok, "}")) {
		    if (is_assignment == FALSE) is_lhs_bundle = FALSE;
		    else is_rhs_bundle = FALSE;
		}
		else if (!strcmp(nexttok, ",")) {
		    /* Do nothing;  moving to the next wire or bundle component */
		}
		else if (GetBusTok(&wb, &top->nets) == 0) {
		    if (is_wire) {
			/* Handle bus notation (wires only) */
			if ((nb = BusHashLookup(nexttok, &top->nets)) == NULL)
			    nb = Net(top, nexttok);
			if (nb->start == -1) {
			    nb->start = wb.start;
			    nb->end = wb.end;
			}
			else {
			    if (nb->start < wb.start) nb->start = wb.start;
			    if (nb->end > wb.end) nb->end = wb.end;
			}
		    }
		    else {
			/* "assign" to a bus subnet.  This will be ignored  */
			/* until this tool handles bus joining.  If the	    */
			/* assignment is made on an undeclared wire, then   */
			/* adjust the wire bounds.			    */
			if (nb && nb->start == -1) {
			    nb->start = wb.start;
			    nb->end = wb.end;
			}
		    }
		}
		else {
		    if (is_assignment) {
			char *qptr;
			int idum;

			if (BusHashLookup(nexttok, &top->nets) != NULL) {
			    /* Join nets */
			    /* (WIP) */
			}
			else if ((qptr = strchr(nexttok, '\'')) != NULL) {
			    *qptr = '\0';
			    if (sscanf(nexttok, "%d", &idum) == 1) {
				if ((strchr(qptr + 1, 'x') == NULL) &&
					(strchr(qptr + 1, 'X') == NULL) &&
					(strchr(qptr + 1, 'z') == NULL) &&
					(strchr(qptr + 1, 'Z') == NULL)) {
				    // Power/Ground denoted by, e.g., "vdd = 1'b1".
				    // Only need to record the net, no further action
				    // needed.
				}
				else {
				    fprintf(stdout, "Assignment is not a net "
					    "(line %d).\n", vlinenum);
				    fprintf(stdout, "Module '%s' is not structural "
					    "verilog,  making black-box.\n", top->name);
				    goto skip_endmodule;
				}
			    }
			    *qptr = '\'';
			}
			else {
			    fprintf(stdout, "Assignment is not a net (line %d).\n",
					vlinenum);
			    fprintf(stdout, "Module '%s' is not structural verilog,"
					" making black-box.\n", top->name);
			    goto skip_endmodule;
			}
			is_assignment = FALSE;
		    }
		    else if (BusHashLookup(nexttok, &top->nets) == NULL)
			Net(top, nexttok);
		}
		do {
		    SkipTokNoNewline(VLOG_DELIMITERS);
		} while (nexttok && !strcmp(nexttok, ";"));
	    }
	}
	else if (!strcmp(nexttok, "endmodule")) {
	    // No action---new module is started with next 'module' statement,
	    // if any.
	    SkipNewLine(VLOG_DELIMITERS);
	}
	else if (nexttok[0] == '`') {
	    // Ignore any other directive starting with a backtick
	    SkipNewLine(VLOG_DELIMITERS);
	}
	else if (!strcmp(nexttok, "reg") || !strcmp(nexttok, "always") ||
		!strcmp(nexttok, "specify") || !strcmp(nexttok, "initial")) {
	    fprintf(stdout, "Behavioral keyword '%s' found in source.\n", nexttok);
	    fprintf(stdout, "Module '%s' is not structural verilog, making "
			"black-box.\n", top->name);
	    goto skip_endmodule;
	}
	else {	/* module instances */
	    char ignore;
	    int itype, arraymax, arraymin;
	    struct instance *thisinst;

	    thisinst = AppendInstance(top, nexttok);

	    SkipTokComments(VLOG_DELIMITERS);

nextinst:
	    ignore = FALSE;

	    // Next token must be '#(' (parameters) or an instance name

	    if (!strcmp(nexttok, "#(")) {

		// Read the parameter list
		SkipTokComments(VLOG_DELIMITERS);

		while (nexttok != NULL) {
		    char *paramname;

		    if (!strcmp(nexttok, ")")) {
			SkipTokComments(VLOG_DELIMITERS);
			break;
		    }
		    else if (!strcmp(nexttok, ",")) {
			SkipTokComments(VLOG_DELIMITERS);
			continue;
		    }

		    // We need to look for parameters of the type ".name(value)"

		    else if (nexttok[0] == '.') {
			paramname = strdup(nexttok + 1);
			SkipTokComments(VLOG_DELIMITERS);
			if (strcmp(nexttok, "(")) {
			    fprintf(stdout, "Error: Expecting parameter value, "
					"got %s (line %d).\n", nexttok, vlinenum);
			}
			SkipTokComments(VLOG_DELIMITERS);
			if (!strcmp(nexttok, ")")) {
			    fprintf(stdout, "Error: Parameter with no value found"
					" (line %d).\n", vlinenum);
			}
			else {
			    HashPtrInstall(paramname, strdup(nexttok),
					&thisinst->propdict); 
			    SkipTokComments(VLOG_DELIMITERS);
			    if (strcmp(nexttok, ")")) {
				fprintf(stdout, "Error: Expecting end of parameter "
					"value, got %s (line %d).\n", nexttok,
					vlinenum);
			    }
			}
			free(paramname);
		    }
		    SkipTokComments(VLOG_DELIMITERS);
		}
		if (!nexttok) {
		    fprintf(stdout, "Error: Still reading module, but got "
				"end-of-file.\n");
		    goto skip_endmodule;
		}
	    }

	    thisinst->instname = strdup(nexttok);

	    /* fprintf(stdout, "Diagnostic:  new instance is %s\n",	*/
	    /*			thisinst->instname);			*/
	    SkipTokComments(VLOG_DELIMITERS);

	    thisinst->arraystart = thisinst->arrayend = -1;
	    if (!strcmp(nexttok, "[")) {
		// Handle instance array notation.
		struct netrec wb;
		if (GetBusTok(&wb, NULL) == 0) {
		    thisinst->arraystart = wb.start;
		    thisinst->arrayend = wb.end;
		}
	    }

	    if (!strcmp(nexttok, "(")) {
		char savetok = (char)0;
		struct portrec *new_port;
		struct netrec *nb, wb;
		char in_line = FALSE, *in_line_net = NULL;
		char *ncomp, *nptr;

		// Read the pin list
		while (nexttok != NULL) {
		    SkipTokComments(VLOG_DELIMITERS);
		    // NOTE: Deal with `ifdef et al. properly.  Ignoring for now.
		    while (nexttok[0] == '`') {
			SkipNewLine(VLOG_DELIMITERS);
			SkipTokComments(VLOG_DELIMITERS);
		    }
		    if (!strcmp(nexttok, ")")) break;
		    else if (!strcmp(nexttok, ",")) continue;

		    // We need to look for pins of the type ".name(value)"

		    if (nexttok[0] != '.') {
			fprintf(stdout, "Ignoring subcircuit with no pin names "
				"at \"%s\" (line %d)\n",
				nexttok, vlinenum);
			while (nexttok != NULL) {
			    SkipTokComments(VLOG_DELIMITERS);
			    if (match(nexttok, ";")) break;
			}
			ignore = TRUE;
			break;
		    }
		    else {
			new_port = InstPort(thisinst, strdup(nexttok + 1), NULL);
			SkipTokComments(VLOG_DELIMITERS);
			if (strcmp(nexttok, "(")) {
			    fprintf(stdout, "Badly formed subcircuit pin line "
					"at \"%s\" (line %d)\n", nexttok, vlinenum);
			    SkipNewLine(VLOG_DELIMITERS);
			}
			SkipTokComments(VLOG_PIN_CHECK_DELIMITERS);
			if (!strcmp(nexttok, ")")) {
			    char localnet[100];
			    // Empty parens, so create a new local node
			    savetok = (char)1;
			    sprintf(localnet, "_noconnect_%d_", localcount++);
			    new_port->net = strdup(localnet);
			}
			else {

			    if (!strcmp(nexttok, "{")) {
				char *in_line_net = (char *)malloc(1);
				*in_line_net = '\0';
				/* In-line array---Read to "}" */
				while (nexttok) {
				    in_line_net = (char *)realloc(in_line_net,
						strlen(in_line_net) +
						strlen(nexttok) + 1);
				    strcat(in_line_net, nexttok);
				    if (!strcmp(nexttok, "}")) break;
				    SkipTokComments(VLOG_PIN_CHECK_DELIMITERS);
				}
				if (!nexttok) {
				    fprintf(stderr, "Unterminated net in pin %s "
						"(line %d)\n", in_line_net,
						vlinenum);
				}
				new_port->net = in_line_net;
			    }
			    else
				new_port->net = strdup(nexttok);

			    /* Read array information along with name;	*/
			    /* will be parsed later 			*/

			    SkipTokComments(VLOG_DELIMITERS);
			    if (!strcmp(nexttok, "[")) {
				/* Check for space between name and array identifier */
				SkipTokComments(VLOG_PIN_NAME_DELIMITERS);
				if (strcmp(nexttok, ")")) {
				    char *expnet;
				    expnet = (char *)malloc(strlen(new_port->net)
						+ strlen(nexttok) + 3);
				    sprintf(expnet, "%s [%s", new_port->net, nexttok);
				    free(new_port->net);
				    new_port->net = expnet;
				}
				SkipTokComments(VLOG_DELIMITERS);
			    }
			    if (strcmp(nexttok, ")")) {
				fprintf(stdout, "Badly formed subcircuit pin line "
					"at \"%s\" (line %d)\n", nexttok, vlinenum);
				SkipNewLine(VLOG_DELIMITERS);
			    }
			}

			/* Register wire if it has not been already, and if it	*/
			/* has been registered, check if this wire increases	*/
			/* the net bounds.  If the net name is an in-line	*/
			/* vector, then process each component separately.	*/

			ncomp = new_port->net;
			while (isdigit(*ncomp)) ncomp++;
			if (*ncomp == '{') ncomp++;
			while (isspace(*ncomp)) ncomp++;
			while (*ncomp != '\0') {
			    int is_esc = FALSE;
			    char saveptr;

			    /* NOTE:  This follows same rules in strdtok() */
			    nptr = ncomp;
			    if (*nptr == '\\') is_esc = TRUE;
			    while (*nptr != ',' && *nptr != '}' && *nptr != '\0') {
				if (*nptr == ' ') {
				    if (is_esc == TRUE)
					is_esc = FALSE;
				    else
					break;
				}
				nptr++;
			    }
			    saveptr = *nptr;
			    *nptr = '\0';

			    /* Parse ncomp as a net or bus */
			    if ((nb = BusHashLookup(ncomp, &top->nets)) == NULL)
				nb = Net(top, ncomp);

			    GetBus(ncomp, &wb, &top->nets);
			    if (nb->start == -1) {
				nb->start = wb.start;
				nb->end = wb.end;
			    }
			    else {
				if (nb->start < wb.start) nb->start = wb.start;
				if (nb->end > wb.end) nb->end = wb.end;
			    }

			    *nptr = saveptr;
			    if (*new_port->net != '{')
				break;

			    ncomp = nptr + 1;
			    /* Skip over any whitespace at the end of a name */
			    while ((*ncomp != '\0') && (*ncomp == ' '))
				ncomp++;
			    while ((*ncomp != '\0') && (*nptr == ',' || *nptr == '}'))
				ncomp++;
			}
		    }
		}
	    }
	    else {
		fprintf(stdout, "Expected to find instance pin block but got "
				"\"%s\" (line %d)\n", nexttok, vlinenum);
	    }
	    if (ignore == TRUE) continue;	/* moving along. . . */

	    /* Verilog allows multiple instances of a single cell type to be	*/
	    /* chained together in a comma-separated list.			*/

	    SkipTokComments(VLOG_DELIMITERS);
	    if (!strcmp(nexttok, ",")) {
		goto nextinst;
	    }

	    /* Otherwise, instance must end with a semicolon */

	    else if (strcmp(nexttok, ";")) {
		fprintf(stdout, "Expected to find end of instance but got "
				"\"%s\" (line %d)\n", nexttok, vlinenum);
	    }
	}
	continue;

skip_endmodule:
	/* There was an error, so skip to the end of the	*/
	/* subcircuit definition				*/

	while (1) {
	    SkipNewLine(VLOG_DELIMITERS);
	    SkipTokComments(VLOG_DELIMITERS);
	    if (EndParseFile()) break;
	    if (!strcmp(nexttok, "endmodule")) {
		in_module = 0;
		break;
	    }
	}
	continue;

baddevice:
	fprintf(stderr, "Badly formed line in input (line %d).\n", vlinenum);
    }

    /* Watch for bad ending syntax */

    if (in_module == (char)1) {
	fprintf(stderr, "Missing \"endmodule\" statement in module.\n");
	InputParseError(stderr);
    }

    /* Make sure topmost cell is on stack before returning */
    PushStack(top, CellStackPtr);

    if (warnings)
	fprintf(stderr, "File %s read with %d warning%s.\n", fname,
		warnings, (warnings == 1) ? "" : "s");
}

/*----------------------------------------------*/
/* Free memory associated with a cell		*/
/*----------------------------------------------*/

/*----------------------------------------------*/
/* Free memory associated with property hash	*/
/*----------------------------------------------*/

int freeprop(struct hashlist *p)
{
    char *propval;

    propval = (char *)(p->ptr);
    free(propval);
    return 1;
}

/*----------------------------------------------*/
/* Top-level verilog module file read routine	*/
/*----------------------------------------------*/

struct cellrec *ReadVerilogTop(char *fname, int blackbox)
{
    struct cellstack *CellStackPtr = NULL;
    struct cellrec *top;
  
    if ((OpenParseFile(fname)) < 0) {
	fprintf(stderr, "Error in Verilog file read: No file %s\n", fname);
	return NULL;
    }

    if (dictinit == FALSE) {
	/* verilogdefs may be pre-initialized by calling VerilogDefine() */
	InitializeHashTable(&verilogdefs, TINYHASHSIZE);
	dictinit = TRUE;
    }
    InitializeHashTable(&verilogparams, TINYHASHSIZE);
    InitializeHashTable(&verilogvectors, TINYHASHSIZE);

    ReadVerilogFile(fname, &CellStackPtr, blackbox);
    CloseParseFile();

    RecurseHashTable(&verilogparams, freeprop);
    HashKill(&verilogparams);
    RecurseHashTable(&verilogdefs, freeprop);
    HashKill(&verilogdefs);

    if (CellStackPtr == NULL) return NULL;

    top = CellStackPtr->cell;
    free(CellStackPtr);
    return top;
}

/*--------------------------------------*/
/* Wrappers for ReadVerilogTop()	*/
/*--------------------------------------*/

struct cellrec *ReadVerilog(char *fname)
{
    return ReadVerilogTop(fname, 0);
}

/*--------------------------------------*/
/* Verilog file include routine		*/
/*--------------------------------------*/

void IncludeVerilog(char *fname, struct cellstack **CellStackPtr, int blackbox)
{
    int filenum = -1;
    char name[256];

    name[0] = '\0';

    /* If fname does not begin with "/", then assume that it is	*/
    /* in the same relative path as its parent.			*/
  
    if (fname[0] != '/') {
	char *ppath;
	if (*CellStackPtr && ((*CellStackPtr)->cell != NULL)) {
	    strcpy(name, (*CellStackPtr)->cell->name);
	    ppath = strrchr(name, '/');
	    if (ppath != NULL)
		strcpy(ppath + 1, fname);
	    else
		strcpy(name, fname);
	    filenum = OpenParseFile(name);
	}
    }

    /* If we failed the path relative to the parent, then try 	*/
    /* the filename alone (relative to the path where netgen	*/
    /* was executed).						*/

    if (filenum < 0) {
	if ((filenum = OpenParseFile(fname)) < 0) {
	    if (filenum < 0) {
		fprintf(stderr,"Error in Verilog file include: No file %s\n",
			    (*name == '\0') ? fname : name);
		return;
	    }    
	}
    }
    ReadVerilogFile(fname, CellStackPtr, blackbox);
    CloseParseFile();
}

/*------------------------------------------------------*/
/* Free the cellrec structure created by ReadVerilog()	*/
/*------------------------------------------------------*/

void FreeVerilog(struct cellrec *topcell)
{
    struct portrec *port, *dport;
    struct instance *inst, *dinst;

    port = topcell->portlist;
    while (port) {
	if (port->name) free(port->name);
	if (port->net) free(port->net);
	dport = port->next;
	free(port);
	port = dport;
    }
    inst = topcell->instlist;
    while (inst) {
	if (inst->instname) free(inst->instname);
	if (inst->cellname) free(inst->cellname);
	port = inst->portlist;
	while (port) {
	    if (port->name) free(port->name);
	    if (port->net) free(port->net);
	    dport = port->next;
	    free(port);
	    port = dport;
	}
        RecurseHashTable(&inst->propdict, freeprop);
        HashKill(&inst->propdict);
	dinst = inst->next;
	free(inst);
	inst = dinst;
    }

    /* Delete nets hashtable */
    RecurseHashTable(&topcell->nets, freenet);
    HashKill(&topcell->nets);

    /* Delete properties hashtable. */
    RecurseHashTable(&topcell->propdict, freeprop);
    HashKill(&topcell->propdict);
}


// readverilog.c