-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvparse.py
More file actions
1737 lines (1651 loc) · 60.9 KB
/
Copy pathvparse.py
File metadata and controls
1737 lines (1651 loc) · 60.9 KB
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
#! /usr/bin/python3
# Very much WIP
# Parse a single Verilog file with no preprocessing
# Parse file rules:
# 1. Macros are defined by line breaks! Need to handle them in initial reading stage
# 1a. Preserve the line break on these lines only
# 2. Keep track of context with respect to multi-line comments
# 3. Remove comments and store along with line start, stop
# Need Stateful Parsing:
# State by scope
# STATE_TOP // top-level
# STATE_IN_BEGIN // waiting for 'end' keyword; needs to be nestable
# others??
import os
import re
def _int(x):
try:
return int(x)
except ValueError:
pass
try:
return int(x, 16)
except ValueError:
return None
class ModuleInstantiation():
def __init__(self, modname, instname, parammap, portmap):
self.modname = modname
self.instname = instname
self.paramMap = parammap
self.portMap = portmap
def __str__(self):
ll = [
"ModuleInstantiation():",
" instance {} of module {}".format(self.instname, self.modname),
]
if len(self.paramMap) > 0:
ll.append(" Param Map")
for pname, pval in self.paramMap:
ll.append(" .{}({})".format(pname, pval))
if len(self.portMap) > 0:
ll.append(" Port Map")
for pname, pval in self.portMap:
ll.append(" .{}({})".format(pname, pval))
return "\n".join(ll)
def getPortConnection(self, portName=None, index=None):
if portName is not None:
for name, val in self.portMap:
if portName == name:
return val
if index is not None and index < len(self.portMap):
return self.portMap[index][1]
return None
def getParamValue(self, paramName=None, index=None):
if paramName is not None:
for name, val in self.paramMap:
if paramName == name:
return val
if index is not None and index < len(self.paramMap):
return self.paramMap[index][1]
return None
class _ModuleInstantiationHelper():
def __init__(self, modname, instname, parammap, portmap):
self.modname = modname.strip()
self.instname = instname.strip()
self._parammap = parammap.strip()
self._portmap = portmap.strip()
self.parse()
def get(self):
return ModuleInstantiation(self.modname, self.instname, self.paramMap, self.portMap)
def parse(self):
self.paramMap = self._parseParamMap(self._parammap)
self.portMap = self._parsePortMap(self._portmap)
return
def __repr__(self):
return self.__str__()
def __str__(self):
ll = [
"_ModuleInstantiationHelper():",
" instance {} of module {}".format(self.instname, self.modname),
]
if len(self.paramMap) > 0:
ll.append(" Param Map")
for pname, pval in self.paramMap:
ll.append(" .{}({})".format(pname, pval))
if len(self.portMap) > 0:
ll.append(" Port Map")
for pname, pval in self.portMap:
ll.append(" .{}({})".format(pname, pval))
return "\n".join(ll)
@classmethod
def _parseParamMap(cls, line):
return cls._parsePortMap(line)
@classmethod
def _parsePortMap(cls, line):
_map = []
# Remove outer parens
line = line.strip()
if len(line) == 0:
return _map
if (line[0] == '(') and (line[-1] == ')'):
line = line[1:-1]
pdecs = cls._splitByCommas(line)
for pdec in pdecs:
name, value = cls._parsePortDec(pdec)
_map.append((name, value))
return _map
@staticmethod
def _parsePortDec(line):
# Handle two types:
# 1. Positional
# foo
# bar[4:0]
# 8'ha5
# 2. Named
# .foo(foo)
# .foo(bar[4:0])
# .foo(8'ha5)
line = line.strip()
restr = "\.([^(]+)\((.+)\)"
_match = re.match(restr, line)
if _match:
# Named type
name, value = _match.groups()
else:
# Positional type
name = ""
value = line
return (name, value)
@staticmethod
def _splitByCommas(line):
return VParser._splitByCommas(line)
class VParser():
# = Regexps =
# Hit on any Verilog module declaration
reVModDecl = "module\s+([A-Za-z_][A-Za-z_0-9]*)\s+([^;]+);$"
# Hit on any port declaration
reVPortDecl = "^(input|output|inout)(\s+wire|\s+reg)?\s*(\[[^\]]+\])?\s+([A-Za-z0-9_]+)\s*,?$"
# Hit on any Verilog integer literal
reVLitHit = "([^\[\]:,.\s+-]+)"
# Hit on any decimal (baseless) integer literal
reVLitDec = "([\d_]+)?"
# Hit on a Verilog integer literal with explicit base
reVLitBase = "(\d+)?\s*('[hHbBdD])\s*([0-9a-fA-F_]+)"
# Hit on any pair of Verilog indices
reVIndices = "^\[?\s*([^\[\]:]+)\s*([+\-]?)\s*:\s*([^\[\]:]+)\s*\]?$"
# Hit on any single Verilog index
reVIndex = "^\[?\s*([^\[\]:]+)\s*\]?$"
# Hit on a pair of Verilog indices as explicit integer literals
reVIndicesLit = "^\[?\s*"+reVLitHit+"\s*([+\-]?)\s*:\s*"+reVLitHit+"\s*\]?$"
# Hit on a single Verilog index as explicit integer literal
reVIndexLit = "^\[?\s*"+reVLitHit+"\s*\]?$"
# Helper values
LINETYPE_PARAM = 0
LINETYPE_PORT = 0
LINETYPE_MACRO = 1
LINETYPE_UNKNOWN = 2
LINETYPE_MODULE_DECLARATION = 3
LINETYPE_MODULE_INSTANTIATION = 4
LINETYPE_INITIAL_BEGIN_BLOCK = 5
LINETYPE_INITIAL_LINE = 6
LINETYPE_ALWAYS_BEGIN_BLOCK = 7
LINETYPE_ALWAYS_LINE = 8
LINETYPE_ASSIGN = 9
LINETYPE_PARAMETER = 10
LINETYPE_LOCALPARAM = 11
LINETYPE_GENERATE = 12
LINETYPE_SYSCALL = 13
LINETYPE_REG = 14
LINETYPE_WIRE = 15
def __init__(self, filename = ""):
self.filename = filename
self.valid = False
self.modname = ""
self.ports = []
self.params = []
self._parsed = False
self._parsedModDecl = False
# A list to contain any modules instantiated within the parent module
self.instantiated_modules = []
self.readFile()
def readFile(self):
if not os.path.exists(self.filename):
print(f"{self.filename} does not exist")
return
nline = 0
multi = False # In multi-line comment
comments = {}
with open(self.filename, 'r') as fd:
procLine = ""
ncomment = 0
line = True
while line:
line = fd.readline()
nline += 1
# =========== Remove End-of-Line Comments ============
segs = self._splitEndComment(line)
codeLine = segs[0]
if len(segs) > 1:
eolcomment = segs[1]
comments[nline] = commentLine
if True:
# NEW-style
# =========== Handle Multi-Line Comments ============
ncomment, codeLine, commentLine = self.commentLevel(codeLine, ncomment)
if len(commentLine) > 0:
comments[nline] = commentLine
if len(codeLine) == 0:
continue
procLine += codeLine
linetype, iscomplete = self.isComplete(procLine)
if iscomplete:
print(f"processing (linetype {linetype}): {procLine}")
self.process(procLine, linetype)
procLine = ""
else:
#print(f"Not processing: {procLine}")
pass
else:
# OLD-style
if multi:
comment, line, ends = self.endsComment(line)
if len(comment) > 0:
comments[nline] = comment
if ends:
multi = False
else:
line, comment, multi = self.hasComment(line)
if len(comment) > 0:
comments[nline] = comment
procLine += line
linetype, iscomplete = self.isComplete(procLine)
if iscomplete:
#print(f"processing: {procLine}")
self.process(procLine, linetype)
procLine = ""
self._parsed = True
#print("COMMENTS")
#for nline, comment in comments.items():
# print(f"[{nline}] : {comment}", end='')
#printSummary()
self.valid = True
return
@staticmethod
def commentLevel(line, ncomment=0):
"""
Returns (ncomment, codestring, commentstring)
'ncomment':
+1: the line enters a multi-line comment.
-1: the line exits a multi-line comment.
0: the line both exits and enters a multi-line comment.
0: the line neither enters nor exits a multi-line comment.
'codestring' is any portion of the line that is not within a comment (could be empty)
'commentstring' is any portion of the line that is within a comment (could be empty)
"""
ml_in = "/*"
ml_out = "*/"
out_lines = []
in_lines = []
if ncomment > 0:
line_in = line
line_out = ""
else:
line_in = ""
line_out = line
if (ml_in not in line_out) and (ml_out not in line_in):
return (ncomment, line_out, line_in)
while (ml_in in line_out) or (ml_out in line_in):
# Handle entering comments
if ml_in in line_out:
line_out, line_in = line_out.split(ml_in, maxsplit=1)
out_lines.append(line_out)
line_out = ""
ncomment += 1
# Handle exiting comments
if ml_out in line_in:
line_in, line_out= line_in.split(ml_out, maxsplit=1)
in_lines.append(line_in)
line_in = ""
ncomment -= 1
out_lines.append(line_out)
in_lines.append(line_in)
return (ncomment, "".join(out_lines), "".join(in_lines))
def getPorts(self):
"""Return list of (linetype, name, dirstr, rangeStart, rangeEnd), one for
each port in the parsed module. If linetype is 1 (self.LINETYPE_MACRO), the
'name' is actually a string of an entire macro line ('dirstr', 'rangeStart'
and 'rangeEnd' are all None in this case). If linetype is 0 (self.LINETYPE_PORT),
it is a normal port where 'rangeStart' and 'rangeEnd' can be None, indicating
a single-bit signal."""
return self.ports
def getParams(self):
"""Return list of (linetype, name, rspec, val), one for each parameter in the
parsed module. If linetype is 1 (self.LINETYPE_MACRO), the 'name' is actually a
string of an entire macro line ('rspec', 'val' are both None in this case).
If linetype is 0 (self.LINETYPE_PARAM), it is a normal parameter where 'rspec'
can be None, indicating a parameter with no bit range specified."""
return self.params
def getModules(self):
"""Return a list of ModuleInstantiation objects representing all the modules
instantiated within the parent."""
return self.instantiated_modules
def printSummary(self):
print(f"MODULE {self.modname}")
for param in self.params:
linetype, name, rspec, val = param
if linetype == self.LINETYPE_MACRO:
print(f" Macro: {name}")
else:
if len(rspec) > 0:
rspec += " "
print(f" parameter {rspec}{name} = {val}")
for port in self.ports:
linetype, name, dirstr, rangeStart, rangeEnd = port
if linetype == self.LINETYPE_MACRO:
print(f" Macro: {name}")
else:
if rangeStart is not None and rangeEnd is not None:
rstr = f" [{rangeStart}:{rangeEnd}] "
else:
rstr = " "
print(f" {dirstr}{rstr}{name}")
print(f"Instantiated modules:")
for module in self.getModules():
print(module)
return
@classmethod
def isComplete(cls, line):
"""Return True if line is ready for processing. This is tricky because there are
so many top-level cases to handle."""
# TODO
# To handle:
# Module declaration
# Ends in semicolon
# initial and always blocks
# If 'begin' keyword; use context count to find matching 'end' keyword
# Otherwise ends with semicolon
# assign
# Ends in semicolon
# parameter
# Ends in semicolon
# localparam
# Ends in semicolon
# module instantiation
# Ends in semicolon
# generate
# Ends in endgenerate
# macros
# Ends after one line
linetype = cls.lineType(line)
semicolon_enders = (
cls.LINETYPE_MODULE_DECLARATION,
cls.LINETYPE_ASSIGN,
cls.LINETYPE_ALWAYS_LINE,
cls.LINETYPE_INITIAL_LINE,
cls.LINETYPE_PARAMETER,
cls.LINETYPE_LOCALPARAM,
cls.LINETYPE_REG,
cls.LINETYPE_WIRE,
cls.LINETYPE_UNKNOWN, # Let's discard unknown lines at semicolons too
)
if linetype in semicolon_enders:
if line.strip().endswith(';'):
return linetype, True
elif linetype in (cls.LINETYPE_ALWAYS_BEGIN_BLOCK, cls.LINETYPE_INITIAL_BEGIN_BLOCK):
if line.strip().endswith("end"):
return linetype, True
elif linetype == cls.LINETYPE_GENERATE:
if line.strip().endswith("endgenerate"):
return linetype, True
elif linetype == cls.LINETYPE_MACRO:
# Macros end after one line
return linetype, True
return linetype, False
@classmethod
def lineType(cls, line):
# To handle:
# Module declaration
# Ends in semicolon
# initial and always blocks
# If 'begin' keyword; use context count to find matching 'end' keyword
# Otherwise ends with semicolon
# assign
# Ends in semicolon
# parameter
# Ends in semicolon
# localparam
# Ends in semicolon
# module instantiation
# Ends in semicolon
# generate
# Ends in endgenerate
# macros
# Ends after one line
# syscalls:
# Ends in semicolon
# === Handle keyword blocks first (they're easiest)
ls = line.strip()
if ls.startswith("module"):
return cls.LINETYPE_MODULE_DECLARATION
elif ls.startswith("initial"):
lss = ls.split()
if len(lss) > 1 and lss[1].strip() == "begin":
return cls.LINETYPE_INITIAL_BEGIN_BLOCK
else:
return cls.LINETYPE_INITIAL_LINE
elif ls.startswith("always"):
return cls._getLineTypeAlways(ls)
elif ls.startswith("assign"):
return cls.LINETYPE_ASSIGN
elif ls.startswith("parameter"):
return cls.LINETYPE_PARAMETER
elif ls.startswith("localparam"):
return cls.LINETYPE_LOCALPARAM
elif ls.startswith("generate"):
return cls.LINETYPE_GENERATE
elif ls.startswith("reg"):
return cls.LINETYPE_REG
elif ls.startswith("wire"):
return cls.LINETYPE_WIRE
elif ls.startswith("`"):
return cls.LINETYPE_MACRO
# Need additional checks to confirm module instantiation (LINETYPE_MODULE_INSTANTIATION)
return cls.LINETYPE_UNKNOWN
def _getLineTypeAlways(cls, line):
"""Get the LINETYPE of a string 'line' starting with keyword 'always'"""
segs = cls._splitBySpace(line.strip())
# Handle two types:
# always @(posedge clk) [begin]
# always #10 [begin]
if len(segs) == 0 or segs[0].strip() != "always":
return cls.LINETYPE_UNKNOWN
if len(segs) > 1:
if segs[1].strip() == "begin":
return cls.LINETYPE_ALWAYS_BEGIN_BLOCK
if len(segs) > 2:
if segs[2].strip() == "begin":
return cls.LINETYPE_ALWAYS_BEGIN_BLOCK
return cls.LINETYPE_ALWAYS_LINE
@classmethod
def parseModuleInstantiation(cls, line):
# Formats:
# 1: modname instname (....);
# 2: modname #(....) instname (....);
mtype = 1
if '#' in line:
mtype = 2
pix = line.index('#')
if line[pix+1] != '(':
# Don't tolerate whitespace between # and (
# Syntax error or non-module-instantiation
print("Don't tolerate whitespace between # and (")
return None
modname = line[:pix]
paramdec, line = cls._popParens(line[pix+1:])
if '(' not in line:
# Syntax error or non-module-instantiation
print(f"No open parens in line {line}")
return None
pix = line.index('(')
modinst = line[:pix]
if mtype == 1:
paramdec = ""
try:
modname, instname = modinst.split()[0:2]
except ValueError:
# Syntax error or non-module-instantiation
print(f"Can't split {modinst}")
return None
else:
instname = modinst
portmap, trail = cls._popParens(line[pix:])
#print(f"Pop portmap from: {line[pix:]}\n Yields: {portmap} {trail}")
if trail.strip() != ';':
# Syntax error or non-module-instantiation
print(f"No trailing semicolon in {trail}")
return None
return _ModuleInstantiationHelper(modname, instname, paramdec, portmap).get()
@staticmethod
def _popParens(line):
"""Split off the first chunk of line contained within parentheses:
E.g. if line == "(foo(), bar(bop())) lorem ipsum", then
returns ("(foo(), bar(bop()))", " lorem ipsum")
"""
if not '(' in line:
return ("", line)
#pix = line.index('(')
plevel = 0
escaped = False
instring = False
foundParen = False
n = 0
for n in range(len(line)):
c = line[n]
if c == '"':
if not escaped:
if instring:
instring = False
else:
instring = True
escaped = False
elif c == '\\':
if not escaped:
escaped = True
else:
escaped = False
elif c == '(':
if not instring and not escaped:
foundParen = True
plevel += 1
escaped = False
elif c == ')':
if not instring and not escaped:
plevel -= 1
escaped = False
if foundParen and plevel == 0:
break
return (line[:n+1], line[n+1:])
@staticmethod
def _splitBySpace(line):
"""Split line by whitespace, respecting parentheses and quotes"""
segments = cls._splitByCharacters(line, (' ', '\n', '\t'))
_segments = []
# Filter out any empty strings
for segment in segments:
if len(segment) > 0:
_segments.append(segment)
return _segments
@classmethod
def _splitByCommas(cls, line):
"""Split line by commas, respecting parentheses and quotes"""
return cls._splitByCharacters(line, (',',))
@staticmethod
def _splitByCharacters(line, splitchars=(',',)):
"""Split line by any chars in 'splitchars', respecting parentheses and quotes"""
# Handle explicit simple case first
inline = False
for char in splitchars:
if char in line:
inline = True
if not inline:
return [line]
ixs = []
plevel = 0
escaped = False
instring = False
for n in range(len(line)):
c = line[n]
if c == '"':
if not escaped:
if instring:
instring = False
else:
instring = True
escaped = False
elif c == '\\':
if not escaped:
escaped = True
else:
escaped = False
elif c == '(':
if not instring and not escaped:
plevel += 1
escaped = False
elif c == ')':
if not instring and not escaped:
plevel -= 1
escaped = False
elif c in splitchars:
if not instring and not escaped and plevel == 0:
ixs.append(n)
escaped = False
segments = []
ixlast = 0
for n in range(len(ixs)):
segments.append(line[ixlast:ixs[n]])
ixlast = ixs[n]+1
segments.append(line[ixlast:])
return segments
@classmethod
def _splitEndComment(cls, line):
return cls._splitByString(line, splitstr="//", respect_quotes=True, respect_parens=False, allow_escape=False, max_splits=1)
@staticmethod
def _splitByString(line, splitstr="", respect_quotes=True, respect_parens=True, allow_escape=True, max_splits=0):
"""Split line by string 'splitstr', respecting parentheses and quotes"""
# Handle explicit simple case first
sl = len(splitstr)
if (sl == 0) or (len(line) < sl):
return [line]
chars = [c for c in line[:len(splitstr)]]
ixs = []
plevel = 0
escaped = False
instring = False
for n in range(len(splitstr)-1, len(line)):
# Shift register
c = line[n]
chars = chars[1:] + [c]
if c == '"':
if not escaped:
if instring:
instring = False
else:
instring = True
escaped = False
elif c == '\\':
if allow_escape:
if not escaped:
escaped = True
else:
escaped = False
elif c == '(':
if respect_parens:
if not instring and not escaped:
plevel += 1
escaped = False
elif c == ')':
if respect_parens:
if not instring and not escaped:
plevel -= 1
escaped = False
elif "".join(chars) == splitstr:
if not instring and not escaped and plevel == 0:
ixs.append(n)
if len(ixs) == max_splits:
break
escaped = False
segments = []
ixlast = 0
for n in range(len(ixs)):
segments.append(line[ixlast:ixs[n]-(sl-1)])
ixlast = ixs[n]+1
segments.append(line[ixlast:])
return segments
def process(self, line, linetype=LINETYPE_UNKNOWN):
if not self._parsedModDecl:
print("parseModDecl")
rval = self.parseModDecl(line)
if rval:
self._parsedModDecl = True
self.modname, self.params, self.ports = rval
print(f"rval = {rval}")
if linetype in (self.LINETYPE_UNKNOWN, self.LINETYPE_MODULE_INSTANTIATION):
print("parseModuleInstantiation")
rval = self.parseModuleInstantiation(line)
if rval is not None:
self.instantiated_modules.append(rval)
else:
print(f"Skipping linetype {linetype}")
# Do other stuff like:
# Capture parameters
return
@staticmethod
def hasComment(line):
# TODO - Handle the case of // and /* within strings
"""Split off any end-of-line comments in string 'line'.
returns (line, comment, multi) where 'comment' can be empty string and 'multi' tells
whether the comment begins a multi-line comment"""
try:
ix = line.index('//')
#print(f"Splitting: {line[:ix]}...{line[ix:]}")
return (line[:ix], line[ix:], False)
except ValueError:
pass
try:
ix = line.index('/*')
#print(f"Multi-Splitting: {line[:ix]}...{line[ix:]}")
return (line[:ix], line[ix:], True)
except ValueError:
#print(f"Not splitting: {line}")
return (line, "", False)
@staticmethod
def endsComment(line):
"""Should be used when parsing has already encountered an open multi-line comment
Look for end of multi-line comment and split string.
Returns (comment, code, ends) where 'code' is anything after the comment ends
and 'ends' is a boolean indicating whether the comment ending sequence was found."""
try:
ix = line.index('*/')
return (line[:ix+2], line[ix+2:], True)
except ValueError:
return (line, '', False)
@classmethod
def parseModDecl(cls, line):
"""Note: line should include all text from 'module' to ending semicolon"""
_match = re.search(cls.reVModDecl, line)
if _match:
groups = _match.groups()
modname = groups[0]
#print(f"modname = {modname}")
rval = cls.parseModParamsAndPorts(groups[1])
if rval is None:
return False
paramdec, portdec = rval
if len(paramdec) > 0:
params = cls.parseModParams(paramdec)
else:
params = ()
if len(portdec) > 0:
ports = cls.parseModPorts(portdec)
else:
ports = ()
#print(f" params = {params}")
#print(f" ports = {ports}")
return (modname, params, ports)
return None
@classmethod
def parseModParamsAndPorts(cls, line):
"""Note: line should be all of the test after 'module modname' up to (not including) the
final semicolon."""
split_ix = 0
params = ""
if line.startswith('#'):
pcnt = 0 # Parenthesis count
# Separate params portion
for n in range(len(line)):
c = line[n]
if c == ')':
pcnt -= 1
if pcnt > 0:
params += c
else:
# If we are back at pcnt = 0 and have contents in params, split to ports
if len(params) > 0:
split_ix = n
break
if c == '(':
pcnt += 1
try:
# Look for next opening parenthesis
open_ix = split_ix + line[split_ix:].index('(')
# Look for last closing parenthesis
close_ix = line.rindex(')')
except ValueError:
print("No match")
return None
ports = line[open_ix+1:close_ix]
return (params, ports)
@classmethod
def parseModParams(cls, line):
"""Note: line should be all parameter declarations separated by commas."""
instr = False
bcnt = 0 # Brace count for concatenations
phasename = True # Alternate 'name' and 'val' phase
params = []
# Tricky parsing because parameter values can be strings which could in theory
# include the word 'parameter' and commas and equals signs, etc.
# Also need to handle preprocessor macros!
namestr = ""
valstr = ""
rangespec = ""
phaserange = False
n = 0
while n < len(line):
c = line[n]
if instr:
if c == '"':
instr = False
else:
pstr += line[n]
else:
# Skip the keyword
if line[n:].startswith('parameter'):
n += len('parameter') - 1
else:
if phasename:
# TODO - This is a bit hackish and will be triggered on any backtick ` in the 'name' area
if c == '`': # Capture macro
macrostr = cls.captureLine(line[n:])
n += len(macrostr)
params.append((cls.LINETYPE_MACRO, macrostr.strip(), None, None))
elif c == '[':
phaserange = True
rangespec += c
elif c == ']':
phaserange = False
rangespec += c
elif c == '=':
phasename = False
else:
if phaserange:
rangespec += c
else:
namestr += c
else:
# Look for commas outside of braces
if bcnt == 0:
if c == ',':
params.append((cls.LINETYPE_PARAM, namestr.strip(), rangespec.strip(), valstr.strip()))
namestr = ""
valstr = ""
rangespec = ""
phasename = True
else:
valstr += c
if c == '"':
instr = True
elif c == '{':
bcnt += 1
elif c == '}':
bcnt -= 1
n += 1
return params
@classmethod
def parseModPorts(cls, line):
"""Note: line should contain all port declaration text from after the first opening parenthesis
up until and not including the final closing parenthesis."""
# TODO This will break if there's a macro defined with multiple parameters in the ports block
# This also breaks for two macros in a row (no commas)
lines = line.split(',')
ports = []
n = 0
_line = lines[n]
while n < len(lines) - 1:
#for _line in lines:
if _line.strip().startswith('`'): # Capture macro
ix = _line.index('`')
macrostr = cls.captureLine(_line[ix:])
ports.append((cls.LINETYPE_MACRO, macrostr.strip(), None, None, None))
msl = len(macrostr)
#print(f"--------- macrostr = |{macrostr}|")
if ix+msl < len(_line): # More line content to process!
_line = _line[ix+msl:]
#print(f"Continuing with {_line}")
continue
else:
rval = cls.parseModPort(_line.strip())
if rval is not None:
name, dirstr, rangeStart, rangeEnd = rval
ports.append((cls.LINETYPE_PORT, name, dirstr, rangeStart, rangeEnd))
else:
raise SyntaxError(f"Unknown line in port declaration: {_line}")
n += 1
_line = lines[n]
return ports
@classmethod
def parseModPort(cls, line):
"""Note: line should be a single port declaration with no trailing comma"""
_match = re.match(cls.reVPortDecl, line)
if _match:
groups = _match.groups()
dirstr, typestr, rangestr, name = groups
# Enforce reserved keyword syntax rules
if name in ('reg', 'wire'):
return None
rangeStart, rangeEnd = cls.splitRange(rangestr)
return (name.strip(), dirstr.strip(), rangeStart, rangeEnd)
return None
@classmethod
def splitRange(cls, rstr):
"""Split range string [start:end] into (start, end) where 'start' and 'end' are both
strings (not evaluated)."""
if rstr is None:
return (None, None)
if ':' not in rstr:
return (None, None)
try:
# Look for opening bracket
open_ix = rstr.index('[')
# Look for closing bracket
close_ix = rstr.rindex(']')
rstr = rstr[open_ix+1:close_ix]
except ValueError:
# Range string is not enclosed in brackets
return (None, None)
return [x.strip() for x in rstr.split(':')]
@staticmethod
def captureLine(line):
"""Very simply just capture and return the first line (up to line break) in string 'line'"""
_match = re.search("\r\n|\n", line)
if _match:
ix = _match.end()
return line[:ix]
return line
@classmethod
def captureMacro(cls, line):
"""Capture a preprocessor macro line from the start of 'line' and return it."""
if not line.startswith('`'):
print("No start")
return None
_match = re.match("`(ifdef|ifndef|if|define|undef|else|elsif|endif)", line)
end = 0
nexpr = 0
if _match:
kw = _match.groups()[0]
print(f"match: kw = {kw}")
end = _match.end()
if kw.strip() in ('if', 'ifdef', 'elsif', 'undef'):
nexpr = 1
elif kw.strip() in ('define',):
nexpr = 2
else:
print("No match")
exprs = []
ix = end + 1
for n in range(nexpr):
expr = cls.captureExpression(line[ix:])
ix += len(expr)
if ix == len(line)-1:
ix = len(line)
#print(f"returning \"{line[:ix]}\"")
return line[:ix]
@staticmethod
def captureExpression(line):
"""Capture a string representing a single boolean line and return it unaltered."""
# Go char-by-char with lookahead to next non-white char
# Need to use syntax to understand when an expression ends
# If we see an operator, we need to know the next non-white char to check for proper usage
chatter = False
def p(*args, **kwargs):
if chatter:
print(*args, **kwargs)
p(f"line = {line}")
def isw(s):
_match = re.match("\s", s)
if _match:
return True
return False
def w(s):
_match = re.search("\s", s)
if _match:
return _match.start()
return None
def nw(s):
_match = re.search("\S", s)
if _match:
return _match.start()
return None
def bop(s):
"""Test if s starts with a binary operator"""
_match = re.match("^\(|==|!=|<=|>=|<<|>>|[^>]>|[^<]<|\+|-|\*|/", s)
p(f"bop? {s[:2]}", end='')
if _match:
p(f" Yes, {s[:_match.end()]}")
return _match.end()
p(" No")
return None
cplt = True # Binary operator complete
n = nw(line)
nonwhite = True
while n < len(line):
c = line[n]
if nonwhite and isw(c):
p(f"Found white at {n}")
nonwhite = False
# Found whitespace. Need to look ahead to next nonwhite
nn = nw(line[n:])
if nn is not None:
n += nn
p(f"Next nonwhite at {n}")
nonwhite = True