-
Notifications
You must be signed in to change notification settings - Fork 1
/
vampyre.py
8544 lines (8113 loc) · 361 KB
/
vampyre.py
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/env python
""" VAMPyRE
Verilog-A Model Pythonic Rule Enforcer
version 1.9.4, 17-Apr-2024
intended for checking for issues like:
1) hidden state (variables used before assigned)
or conditionally-assigned operating point values
2) unused parameters, variables, ports, or nodes
3) division by zero for parameters (1/parm where parm's range allows 0)
or domain errors for ln() and sqrt()
4) integer division (1/2 = 0)
5) incorrect ddx() usage
6) ports without direction and/or discipline
7) incorrect access functions for discipline
8) unnamed noise sources
9) use of features not appropriate for compact models
10) various issues of poor coding style
11) compliance with CMC Verilog-A Code Standards:
- use of lowercase identifiers
- proper use of tref and dtemp
- proper use of the multiplicity attribute
- proper implementation of mult_i, mult_q, mult_fn
12) misuse of limexp
13) various problems with binning equations and units
14) nonlinear ddt() expressions and C(V)*ddt(V) formulations
15) superfluous assignments
16) order-of-operation problems with macro expansions
Copyright (c) 2024 Analog Devices, Inc.
Licensed under Educational Community License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may
obtain a copy of the license at http://opensource.org/licenses/ECL-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
################################################################################
# setup
import os
import sys
import argparse
from copy import deepcopy
################################################################################
# global variables
gVersionNumber = "1.9.4"
gModuleName = ""
gNatures = {}
gDisciplines = {}
gParameters = {}
gVariables = {}
gHiddenState = {}
gUserFunctions = {}
gAccessFuncs = {}
gPortnames = {} # terminals
gPortlist = ""
gNodenames = {} # internal nodes
gBranches = {}
gMultScaled = {}
gContribs = {} # contributions
gBlocknames = {}
gMacros = {}
gIfDefStatus = []
gScopeList = []
gLoopTypes = []
gConditions = [] # if-conditions in play
gCondBiasDep = [] # whether conditions are bias-dependent:
# 0 (no), 1 (from if cond), 2 (yes), 3 (deriv error), 4 (ddx)
gAnalogBlock = [] # analog or analog initial
gMissingConstantsFile = ""
gStatementInCurrentBlock = False
gLastDisplayTask = []
gLastLineWasEvent = False
gCurrentFunc = 0
gFileName = []
gLineNo = []
gSubline = 0
gIncDir = []
gDebug = False
gDefines = []
gFixIndent = False
gMaxNum = 5
gSpcPerInd = 4
gStyle = False
gVerbose = False
gBinning = False
gBinningPatterns = [[], []]
gBinningFactors = {}
gNoiseTypes = []
gSuperfluous = False
gCompactModel = True
gCheckMultFactors = 0
gUsesDDT = False
gPrDefVals = False
gPreProcess = False
# dictionaries to track how many of each type of message
gErrorMsgDict = {}
gWarningMsgDict = {}
gNoticeMsgDict = {}
gStyleMsgDict = {}
# tokens
# (0-255 are ascii and latin-1)
gTokenUnused = 256
gTokenNumber = 257
gTokenIdentifier = 258
gTokenString = 259
# keywords
# from Verilog-AMS Language Reference Manual, version 2.4, Annex B
# VAMS LRM available from https://accellera.org/downloads/standards/v-ams
gVAMSkeywords = [
"above", "abs", "absdelay", "absdelta", "abstol", "access", "acos", "acosh",
"ac_stim", "aliasparam", "always", "analog", "analysis", "and", "asin",
"asinh", "assert", "assign", "atan", "atan2", "atanh", "automatic",
"begin", "branch", "buf", "bufif0", "bufif1",
"case", "casex", "casez", "ceil", "cell", "cmos", "config", "connect",
"connectmodule", "connectrules", "continuous", "cos", "cosh", "cross",
"ddt", "ddt_nature", "ddx", "deassign", "default", "defparam", "design",
"disable", "discipline", "discrete", "domain", "driver_update",
"edge", "else", "end", "endcase", "endconfig", "endconnectrules",
"enddiscipline", "endfunction", "endgenerate", "endmodule", "endnature",
"endparamset", "endprimitive", "endspecify", "endtable", "endtask",
"event", "exclude", "exp",
"final_step", "flicker_noise", "floor", "flow", "for", "force", "forever",
"fork", "from", "function",
"generate", "genvar", "ground",
"highz0", "highz1", "hypot",
"idt", "idtmod", "idt_nature", "if", "ifnone", "incdir", "include", "inf",
"initial", "initial_step", "inout", "input", "instance", "integer",
"join",
"laplace_nd", "laplace_np", "laplace_zd", "laplace_zp", "large",
"last_crossing", "liblist", "library", "limexp", "ln", "localparam", "log",
"macromodule", "max", "medium", "merged", "min", "module",
"nand", "nature", "negedge", "net_resolution", "nmos", "noise_table",
"noise_table_log", "nor", "noshowcancelled", "not", "notif0", "notif1",
"or", "output",
"parameter", "paramset", "pmos", "posedge", "potential", "pow", "primitive",
"pull0", "pull1", "pulldown", "pullup", "pulsestyle_onevent",
"pulsestyle_ondetect",
"rcmos", "real", "realtime", "reg", "release", "repeat", "resolveto",
"rnmos", "rpmos", "rtran", "rtranif0", "rtranif1",
"scalared", "sin", "sinh", "showcancelled", "signed", "slew", "small",
"specify", "specparam", "split", "sqrt", "string", "strong0", "strong1",
"supply0", "supply1",
"table", "tan", "tanh", "task", "time", "timer", "tran", "tranif0",
"tranif1", "transition", "tri", "tri0", "tri1", "triand", "trior", "trireg",
"units", "unsigned", "use", "uwire",
"vectored",
"wait", "wand", "weak0", "weak1", "while", "white_noise", "wire",
"wor", "wreal",
"xnor", "xor",
"zi_nd", "zi_np", "zi_zd", "zi_zp"]
# compiler directives from VAMS LRM Section 10
gVAMScompdir = [
"begin_keywords", "celldefine", "default_discipline", "default_nettype",
"default_transition", "define", "else", "elsif", "end_keywords",
"endcelldefine", "endif", "ifdef", "ifndef", "include", "line",
"nounconnected_drive", "pragma", "resetall", "timescale",
"unconnected_drive", "undef"]
# hierarchical system parameters from VAMS LRM Section 6.3.6
gVAMShiersysparm = ["$xposition", "$yposition", "$angle", "$hflip", "$vflip"]
# operator precedence
gOperatorPrecedence = {"u-": 12, "!": 12, "**": 11, "*": 10, "/": 10, "%": 10,
"+": 9, "-": 9, "<<": 8, ">>": 8, "<<<": 8, ">>>": 8,
"<": 7, "<=": 7, ">": 7, ">=": 7,
"==": 6, "!=": 6, "===": 6, "!==": 6,
"&": 5, "|": 3, "&&": 2, "||": 1}
# math functions and number of arguments
gMathFunctions = {"abs": 1, "limexp": 1, "log": 1, "$log10": 1, "min": 2, "max": 2}
# math functions with both name and $name form
for fn in ["acos", "acosh", "asin", "asinh", "atan", "atanh", "ceil",
"cos", "cosh", "exp", "floor", "ln", "sin", "sinh", "sqrt",
"tan", "tanh"]:
gMathFunctions[fn] = 1
gMathFunctions["$"+fn] = 1
for fn in ["atan2", "hypot", "pow"]:
gMathFunctions[fn] = 2
gMathFunctions["$"+fn] = 2
# not for use in compact models
for fn in ["idtmod", "absdelay", "analysis", "transition", "slew", "last_crossing",
"laplace_nd", "laplace_np", "laplace_zd", "laplace_zp",
"zi_nd", "zi_np", "zi_zd", "zi_zp"]:
gMathFunctions[fn] = 99
# units for multiplicity checking
gUnitsMultiply = ["A", "amp", "amps", "F", "farad", "farads", "C", "coul", "coulomb", "coulombs",
"W", "watt", "watts", "A/V", "S", "mho", "A*V", "A*V/K", "A/K", "C/K",
"J/K", "s*W/K", "A/V^2", "A^2/Hz"]
gUnitsDivide = ["ohm", "ohms", "Ohm", "V/A", "K/W", "V^2/Hz"]
# MULT_* factors
gMultFactors = ["mult_i", "mult_q", "mult_fn", "MULT_I", "MULT_Q", "MULT_FN"]
# for use in asString()
gExprTypeNoExtraParen = ["==", "!=", "<", ">", "<=", ">=", "&&", "||", "!", "NOT", "NAME", "NUMBER", "FUNCCALL"]
################################################################################
# classes
class Nature:
""" Verilog-AMS Nature """
def __init__(self, name, defn):
self.name = name
self.defined = defn # False during pre-processing
self.units = ""
self.access = ""
self.idt_nature = ""
class Discipline:
""" Verilog-AMS Discipline """
def __init__(self, name):
self.name = name
self.potential = ""
self.flow = ""
self.domain = ""
class Parameter:
""" Verilog-AMS Parameter """
def __init__(self, name, type, file, line):
self.name = name
self.type = type # real, integer, string
self.declare = [file, line]
self.defv = 0
self.units = 0
self.range = [] # array parameters
self.value_range = "nb" # nb, cc, co, oc, oo, cz, oz, sw
self.max = float("inf")
self.min = float("-inf")
self.exclude = []
self.inst = False # instance parameter (or both)
self.model = False # model parameter (or both)
self.scale = "" # linear or quadratic
self.used = 0 # number of times used
self.is_alias = False # True for aliasparam (should not be used)
def getValueRangeStr(self):
ret = ""
if self.value_range == "nb":
ret = "(-inf:inf)"
elif self.value_range in ["cc", "co", "oc", "oo"]:
if self.value_range[0] == "c":
lend = "["
else:
lend = "("
if self.value_range[1] == "c":
rend = "]"
else:
rend = ")"
ret = lend + self.min.asString() + ":" + self.max.asString() + rend
#elif self.value_range == "cz":
# ret = "[0:inf)"
#elif self.value_range == "oz":
# ret = "(0:inf)"
#elif self.value_range == "sw":
# ret = "[0:1]"
return ret
class Variable:
""" Verilog-AMS variable """
def __init__(self, name, type, oppt, file, line):
self.name = name
self.type = type # real, integer, string
self.range = []
self.oppt = oppt # operating-point variable
self.units = "" # units (only for oppt)
self.declare = [file, line]
self.assign = -1 # line where value assigned
self.prev_assign = [] # details about previous assignment
self.non_zero_assign = False # true if assigned a non-zero value
self.conditions = [] # conditions when assigned
self.cond_deps = [] # dependencies of assignment conditions
self.accesses = [] # details about assignments and uses
self.used = False # whether used
self.bias_dep = 0 # bias-dependent: 0=no, 1=from if cond, 2=yes, 3=deriv error, 4=ddx
self.biases = [] # node voltages (for ddx check)
self.zeros = [] # parameters that, when zero, make the variable zero
self.factors = [] # factors (for MULT_* checks)
self.ddt_use = 0 # involves ddt: 0=no, 1=linear, 2=nonlinear
self.func_name_arg = ["", 0] # tracing whether function output arg is used
self.integer_vals = [] # bias-independent integer values, if any
class Access:
""" Variable access info """
def __init__(self, type, file, line, subl, cond, zini=0):
self.type = type # "SET" or "USE"
self.file = file
self.line = line
self.subl = subl
self.cond = cond # conditions in effect
self.loop = False # if used in loop
self.zini = zini # initialization to zero
self.used = False
class Port:
""" Verilog-AMS port """
def __init__(self, name, file, line):
self.name = name
self.type = ""
self.direction = "" # inout, input, output
self.discipline = "" # electrical, thermal, ...
self.declare = [file, line]
self.is_bus = False
self.msb = 0
self.lsb = 0
self.mult = False # whether contributions to this node need mult scaling
self.used = False
class Branch:
""" Verilog-AMS branch """
def __init__(self, name):
self.name = name
self.node1 = ""
self.node2 = ""
self.discipline = "" # electrical, thermal, ...
self.conds = [] # conditions under which contributed to
self.lhs_flow = 0 # flow contrib: 0=no, 1=yes, 2=bias-dep condition
self.lhs_pot = 0 # potential contrib: 0=no, 1=yes, 2=bias-dep condition
self.mult = False # whether contributions to this branch need mult scaling
self.used = False
class Contribution:
""" Verilog-AMS contribution """
def __init__(self, acc):
self.acc = acc
self.func = ""
self.node1 = ""
self.node2 = ""
self.branch = ""
self.discipline = ""
class Macro:
""" Verilog-AMS macro """
def __init__(self, name, text):
self.name = name
self.text = text
self.args = []
self.used = False # whether used
class Function:
""" Verilog-AMS function """
def __init__(self, name, type):
self.name = name
self.type = type # real, integer, string
self.args = []
self.inputs = []
self.outputs = []
self.used = False # whether used
self.outarg_used = [] # whether output args are used in any call to the function
class Expression:
""" Verilog-AMS expression """
def __init__(self, type):
self.type = type # NAME, STRING, NUMBER, FUNCCALL, or operator
self.e1 = 0
self.e2 = 0
self.e3 = 0
self.number = 0
self.is_int = False # is the expression an integer?
self.args = []
self.parens = False # whether expression was in (parentheses)
def getDependencies(self, assign_context, branch_contrib, do_warn):
deps = []
if self.type == "NAME":
deps = [self.e1]
elif self.type in ["NUMBER", "STRING"]:
deps = []
elif self.type == "ARRAY":
deps = []
for arg in self.args:
deps += arg.getDependencies(assign_context, branch_contrib, do_warn)
elif self.type == "FUNCCALL":
if self.e1 in gAccessFuncs:
if do_warn and gAnalogBlock and gAnalogBlock[-1] == "initial":
error("Branch access in analog initial block")
nargs = len(self.args)
if nargs > 0:
nname1 = self.args[0].e1
nname2 = ""
if nname1 in gPortnames:
dname = gPortnames[nname1].discipline
gPortnames[nname1].used = True
elif nname1 in gNodenames:
dname = gNodenames[nname1].discipline
gNodenames[nname1].used = True
elif nname1 in gBranches:
dname = gBranches[nname1].discipline
gBranches[nname1].used = True
else:
dname = ""
if dname in gDisciplines:
disc = gDisciplines[dname]
pname = disc.potential
fname = disc.flow
# use "potential" and "flow" to indicate bias-dependence
# (these keywords cannot collide with variable names)
if pname in gNatures and self.e1 == gNatures[pname].access:
#deps.append("potential")
pass
elif fname in gNatures and self.e1 == gNatures[fname].access:
#deps.append("flow")
pass
elif do_warn:
error("Incorrect access function '%s' for %s '%s'"
% (self.e1, dname, nname1))
elif dname == "" and do_warn and not branch_contrib:
# if branch_contrib, error was reported already
error("Cannot determine discipline of '%s'" % nname1)
if nargs > 2 or (nargs > 1 and (nname1 in gBranches or self.args[1].e1 in gBranches)):
if do_warn:
error("Invalid potential or flow access")
elif nargs == 2:
nname2 = self.args[1].e1
dname2 = ""
if nname2 in gPortnames:
dname2 = gPortnames[nname2].discipline
gPortnames[nname2].used = True
elif nname2 in gNodenames:
dname2 = gNodenames[nname2].discipline
gNodenames[nname2].used = True
if dname2 != "" and dname2 != dname and do_warn and not branch_contrib:
# if branch_contrib, error was reported already
error("Nodes '%s' and '%s' belong to different disciplines"
% (nname1, nname2))
if nname1 != "":
if nname1 in gBranches:
dep = self.e1 + "(" + nname1 + ")"
deps.append(dep)
branch = gBranches[nname1]
nname1 = branch.node1
nname2 = branch.node2
dep = self.e1 + "(" + nname1 + ")"
deps.append(dep)
if nname2 != "":
dep = self.e1 + "(" + nname2 + ")"
deps.append(dep)
elif nargs == 0 and do_warn and not branch_contrib:
# if branch_contrib, error was reported already
error("Missing node/branch name in potential or flow access")
elif self.e1 in ["$port_connected", "$param_given"]:
if len(self.args) == 1:
nname = self.args[0].e1
if self.e1 == "$port_connected":
if nname in gPortnames:
gPortnames[nname].used = True
elif do_warn:
error("Invalid argument '%s' to %s, must be a port" % (nname, self.e1))
elif self.e1 == "$param_given":
if nname in gParameters:
gParameters[nname].used += 1
elif do_warn:
error("Invalid argument '%s' to %s, must be a parameter" % (nname, self.e1))
elif do_warn:
error("Incorrect number of arguments to %s" % self.e1)
elif self.e1 == "limexp":
if len(self.args) == 1:
arg = self.args[0]
deps = arg.getDependencies(assign_context, branch_contrib, do_warn)
[bias_dep, biases, ddt] = checkDependencies(deps, "Call to function '%s' depends on"
% self.e1, 0, False, True, False)
if not bias_dep:
warning("Call to %s(%s), but argument is not bias-dependent"
% (self.e1, arg.asString()))
# else: warning issued elsewhere
elif self.e1 == "$limit":
if len(self.args) == 0:
if do_warn:
error("Require at least one argument to %s" % self.e1)
else:
access = self.args[0]
deps += access.getDependencies(assign_context, branch_contrib, do_warn)
if access.type != "FUNCCALL" or access.e1 not in gAccessFuncs and do_warn:
error("First argument to $limit must be a potential or flow access function")
if len(self.args) >= 2:
limfn = self.args[1]
if limfn.type == "NAME":
# identifier: user-defined function
fname = limfn.e1
if fname in gUserFunctions:
gUserFunctions[fname].used = True
elif do_warn:
error("Unknown identifier '%s' specified as limiting function" % fname)
elif limfn.type == "STRING":
# string: simulator function
fname = limfn.e1
if do_warn and fname not in ["\"pnjlim\"", "\"fetlim\""]:
notice("Non-standard limiting function %s" % fname)
elif do_warn:
warning("Second argument to $limit should be a string or identifier")
for arg in self.args[2:]:
argdeps = arg.getDependencies(assign_context, branch_contrib, do_warn)
[bias_dep, biases, ddt] = checkDependencies(argdeps,
"Call to function '%s' depends on"
% self.e1, 0, False, True, False)
deps += argdeps
elif self.e1 == "ddx":
if len(self.args) == 2:
arg = self.args[0]
argdeps = arg.getDependencies(assign_context, branch_contrib, do_warn)
deps = ["ddx"]
deps += argdeps
acc = self.args[1]
# note: acc does not add a dependency if arg does not already depend on acc
if acc.type == "FUNCCALL" and acc.e1 in gAccessFuncs:
accstr = acc.asString()
[bias_dep, biases, ddt] = checkDependencies(argdeps, "Call to ddx() depends on",
0, False, True, False)
if ddt and do_warn:
error("Call to ddx() where argument %s involves ddt()" % arg.asString())
if accstr not in biases and do_warn:
warning("Call to ddx(), but %s does not depend on %s"
% (arg.asString(), acc.asString()))
if gDebug:
print(" Depends on: %s" % biases)
# else error printed during parsing
elif branch_contrib and self.e1 in ["white_noise", "flicker_noise", "noise_table", "noise_table_log",
"laplace_zp", "laplace_zd", "laplace_np", "laplace_nd",
"zi_zp", "zi_zd", "zi_np", "zi_nd"]:
# ignore dependencies in noise functions and laplace and z operators
pass
else:
out_arg_pos = []
if (assign_context or branch_contrib) and self.e1 == "ddt":
deps = ["ddt"]
if assign_context and self.e1 in ["white_noise", "flicker_noise", "noise_table", "noise_table_log"]:
warning("Small-signal noise source '%s' in assignment" % self.e1)
if self.e1 in gUserFunctions:
# find positions of output arguments
funcdef = gUserFunctions[self.e1]
funcdef.used = True
args = funcdef.args
for i in range(len(args)):
if args[i] in funcdef.outputs:
out_arg_pos.append(i)
for i in range(len(self.args)):
arg = self.args[i]
if i in out_arg_pos:
if do_warn and not assign_context:
error("Function '%s' with output arguments called in unexpected context" % self.e1)
elif arg.type == "NOTHING":
pass # null argument
else:
deps += arg.getDependencies(assign_context, branch_contrib, do_warn)
if assign_context and out_arg_pos:
[bias_dep, biases, ddt] = checkDependencies(deps, "Call to function '%s' depends on"
% self.e1, 0, False, False, True)
for i in range(len(self.args)):
if i in out_arg_pos:
arg = self.args[i]
markVariableAsSet(arg.e1, None, [], bias_dep, Expression("NOTHING"),
biases, 0, False, True, self.e1, i)
elif self.type in ["!", "~", "NOT"]:
deps = self.e1.getDependencies(assign_context, branch_contrib, do_warn)
elif self.type in ["+", "-"]:
dep1 = self.e1.getDependencies(assign_context, branch_contrib, do_warn)
if self.e2:
dep2 = self.e2.getDependencies(assign_context, branch_contrib, do_warn)
else: # unary +/-
dep2 = []
deps = dep1 + dep2
elif self.type in ["*", "/", "%", "**",
"==", "!=", "<", ">", "<=", ">=",
"&&", "||", "&", "|", "^"]:
dep1 = self.e1.getDependencies(assign_context, branch_contrib, do_warn)
dep2 = self.e2.getDependencies(assign_context, branch_contrib, do_warn)
deps = dep1 + dep2
if self.type == "*" and "ddt" in deps:
# check for C(V) * ddt(V)
ddt_biases = []
if self.e1.type == "FUNCCALL" and self.e1.e1 == "ddt":
ddt_biases = checkDependencies(dep1, "", 0, False, False, False)[1]
cdep = dep2
elif self.e2.type == "FUNCCALL" and self.e2.e1 == "ddt":
ddt_biases = checkDependencies(dep2, "", 0, False, False, False)[1]
cdep = dep1
if ddt_biases:
biases = checkDependencies(cdep, "", 0, False, False, False)[1]
bad_biases = []
for bias in biases:
if bias in ddt_biases:
bad_biases.append(bias)
if bad_biases:
bias = simplifyBiases(bad_biases)
if do_warn:
error("Non-charge-conserving f(%s) * ddt(%s)" % (bias, bias))
elif self.type in ["<<", ">>", "<<<", ">>>", "===", "!==",
"^~", "~^", "~&", "~|"]:
# not expected in Verilog-A
dep1 = self.e1.getDependencies(assign_context, branch_contrib, do_warn)
dep2 = self.e2.getDependencies(assign_context, branch_contrib, do_warn)
deps = dep1 + dep2
elif self.type in ["?:"]:
dep1 = self.e1.getDependencies(assign_context, branch_contrib, do_warn)
dep2 = self.e2.getDependencies(assign_context, branch_contrib, do_warn)
dep3 = self.e3.getDependencies(assign_context, branch_contrib, do_warn)
deps = dep1 + dep2 + dep3
else: # pragma: no cover
fatal("Unhandled expression type '%s' in getDependencies" % self.type)
return deps
def ddtCheck(self):
ret = 0
if self.type == "NAME":
if self.e1 in gParameters:
ret = 0
else:
vn = findVariableInScope(self.e1)
if vn in gVariables:
ret = gVariables[vn].ddt_use
else: # pragma: no cover
fatal("Unexpected identifier '%s' in ddtCheck" % self.e1)
elif self.type in ["NUMBER", "STRING"]:
ret = 0
elif self.type == "FUNCCALL":
if self.e1 in gAccessFuncs:
ret = 0
elif self.e1 == "ddt":
ret = 1 + self.args[0].ddtCheck()
else:
for arg in self.args:
ddt1 = arg.ddtCheck()
if ddt1 > 0:
ret = 2 # nonlinear
elif self.type in ["+", "-"]:
ddt1 = self.e1.ddtCheck()
if self.e2:
ddt2 = self.e2.ddtCheck()
else:
ddt2 = 0
if ddt1 > ddt2:
ret = ddt1
else:
ret = ddt2
elif self.type in ["*", "/", "%", "**"]:
ddt1 = self.e1.ddtCheck()
ddt2 = self.e2.ddtCheck()
if ddt1 == 0 and ddt2 == 0:
ret = 0
elif ddt1 == 1 and ddt2 == 0 and self.type in ["*", "/"]:
ret = 1
elif ddt1 == 0 and ddt2 == 1 and self.type == "*":
ret = 1
else:
ret = 2 # assume nonlinear
elif self.type in ["?:"]:
ddt1 = self.e1.ddtCheck()
ddt2 = self.e2.ddtCheck()
ddt3 = self.e3.ddtCheck()
if ddt1 == 0:
if ddt2 > ddt3:
ret = ddt2
else:
ret = ddt3
else:
error("ddt() dependence in condition for '?:' operator")
elif self.type in ["!", "~"]:
error("ddt() dependence in operand for '%s' operator" % self.type)
elif self.type in ["==", "!=", "<", ">", "<=", ">=",
"&&", "||", "&", "|", "^",
"<<", ">>", "<<<", ">>>", "===", "!==",
"^~", "~^", "~&", "~|"]:
error("ddt() dependence in operands for '%s' operator" % self.type)
else: # pragma: no cover
fatal("Unhandled expression type '%s' in ddtCheck" % self.type)
return ret
def asString(self):
ret = ""
if self.type in ["NAME", "STRING"]:
ret = self.e1
elif self.type == "NUMBER":
if isinstance(self.e1, str): # original parsed string
ret = self.e1
elif self.is_int:
ret = str(int(self.number))
else:
ret = str(self.number)
elif self.type == "FUNCCALL":
ret = self.e1 + "("
first = True
for arg in self.args:
if first:
first = False
else:
ret += ","
ret += arg.asString()
ret += ")"
elif self.type in ["!", "~"]:
ret = self.type + "(" + self.e1.asString() + ")"
elif self.type == "NOT":
ret = "NOT(" + self.e1.asString() + ")"
elif self.type in ["+", "-"]:
if self.e2:
ret = "(" + self.e1.asString() + self.type + self.e2.asString() + ")"
else: # unary +/-
ret = self.type + "(" + self.e1.asString() + ")"
elif self.type == "&&":
if self.e1.type in gExprTypeNoExtraParen and self.e2.type in gExprTypeNoExtraParen:
ret = self.e1.asString() + "&&" + self.e2.asString()
else:
ret = "(" + self.e1.asString() + self.type + self.e2.asString() + ")"
elif self.type in ["*", "/", "%", "**",
"==", "!=", "<", ">", "<=", ">=",
"||", "&", "|", "^"]:
ret = "(" + self.e1.asString() + self.type + self.e2.asString() + ")"
elif self.type in ["<<", ">>", "<<<", ">>>", "===", "!==",
"^~", "~^", "~&", "~|"]:
# not expected in Verilog-A
ret = "(" + self.e1.asString() + self.type + self.e2.asString() + ")"
elif self.type in ["?:"]:
ret = "(" + self.e1.asString() + ")?(" + self.e2.asString() \
+ "):(" + self.e3.asString() + ")"
elif self.type == "ARRAY":
ret = "'{"
first = True
for arg in self.args:
if first:
first = False
else:
ret += ","
ret += arg.asString()
ret += "}"
elif self.type == "EVENT":
ret = "@("
first = True
for arg in self.args:
if first:
first = False
else:
ret += ","
ret += arg.asString()
ret += ")"
#elif self.type == "PORT_FLOW":
# return "<" + self.e1 + ">"
#elif self.type == "NOTHING":
# return "TODO"
else: # pragma: no cover
fatal("Unhandled expression type '%s' in asString" % self.type)
return ret
class Parser:
""" Parser for Verilog-AMS source code """
def __init__(self, line):
self.line = line
self.chpt = 0
self.end = len(line)
self.token = 0
self.number = 0
self.ternary_cond = Expression("NOTHING")
self.is_int = False
self.escaped = False
self.string = ""
self.parse_units = False
def isNumber(self):
return self.token == gTokenNumber
def isIdentifier(self):
return self.token == gTokenIdentifier
def isString(self):
return self.token == gTokenString
def isEscaped(self):
return self.escaped
def getNumber(self):
return self.number
def getString(self):
return self.string
def getRestOfLine(self):
retstr = self.line[self.chpt:]
self.chpt = self.end
return retstr
def peekRestOfLine(self):
return self.line[self.chpt:]
def eatSpace(self):
while self.peekChar().isspace():
self.getChar()
def peekToken(self):
ret = ""
pcp = self.chpt
while pcp < self.end and self.line[pcp].isspace():
pcp += 1
if pcp < self.end:
ret = self.line[pcp]
return ret
def peekChar(self):
ret = ""
if self.chpt < self.end:
ret = self.line[self.chpt]
return ret
def getChar(self):
ret = ""
if self.chpt < self.end:
ch = self.line[self.chpt]
self.chpt += 1
ret = ch
return ret
def ungetChar(self, ch):
if self.chpt > 0:
self.chpt -= 1
if self.line[self.chpt] != ch: # pragma: no cover
fatal("Parse failure in ungetChar")
def ungetChars(self, chars):
for i in range(len(chars), 0, -1):
ch = chars[i-1]
self.ungetChar(ch)
def lexNumber(self):
value = 0
string = ""
sci_not = ""
is_int = True
while self.peekChar().isdigit():
string += self.getChar()
if self.peekChar() == '.':
string += self.getChar()
is_int = False
while self.peekChar().isdigit():
string += self.getChar()
if self.peekChar() == '.': # pragma: no cover
error("Invalid number")
ch = self.peekChar()
if ch in ['e', 'E']:
sci_not = self.getChar()
ch = self.peekChar()
last_ch = ""
if ch in ['+', '-']:
sci_not += self.getChar()
while self.peekChar().isdigit():
last_ch = self.getChar()
sci_not += last_ch
if last_ch.isdigit():
string += sci_not
is_int = False
else:
self.ungetChars(sci_not)
sci_not = ""
value = float(string)
# if not sci not, look for SI prefixes
if sci_not == "":
ch = self.peekChar()
if ch == 'T':
value *= 1e12
string += self.getChar()
elif ch == 'G':
value *= 1e9
string += self.getChar()
elif ch == 'M':
value *= 1e6
string += self.getChar()
elif ch in ['K', 'k']:
value *= 1e3
string += self.getChar()
elif ch == 'm':
value *= 1e-3
string += self.getChar()
is_int = False
elif ch == 'u':
value *= 1e-6
string += self.getChar()
is_int = False
elif ch == 'n':
value *= 1e-9
string += self.getChar()
is_int = False
elif ch == 'p':
value *= 1e-12
string += self.getChar()
is_int = False
elif ch == 'f':
value *= 1e-15
string += self.getChar()
is_int = False
elif ch == 'a':
value *= 1e-18
string += self.getChar()
is_int = False
return [value, is_int, string]
# end of lexNumber
def lexName(self):
string = ""
while self.peekChar() == '$':
string += self.getChar()
while self.peekChar().isalnum() or self.peekChar() == '_':
string += self.getChar()
return string
def lexString(self, qstr):
string = self.getChar()
ch = ""
escaped = False
while ch != qstr or escaped:
ch = self.getChar()
if ch == "":
error("Missing end-quote %s" % qstr)
if string[-1] == ';':
self.ungetChar(';')
string = string[0:-1]
break
if escaped:
string += ch
ch = " "
escaped = False
elif ch == "\\":
escaped = True
else:
string += ch
return string
def lex(self):
self.eatSpace()
ch = self.peekChar()
if ch == "":
self.token = 0
elif ch.isdigit():
number = self.lexNumber()
self.number = number[0]
self.is_int = number[1]
self.string = number[2]
self.token = gTokenNumber
elif ch.isalpha() or ch == '_' or ch == '$':
self.string = self.lexName()
self.token = gTokenIdentifier
elif ch == '\\':
# escaped identifier
self.string = ""
ch = self.getChar()
ch = self.getChar()
while ch != "" and not ch.isspace():
self.string += ch
ch = self.getChar()
if self.string != "":
self.token = gTokenIdentifier
self.escaped = True
else:
ch = '\\'
self.token = ord(ch)
elif ch == '"':
self.string = self.lexString(ch)
self.token = gTokenString
else:
ch = self.getChar()
if ord(ch) > 127 and not self.parse_units:
error("Encountered non-ASCII character '%s' (decimal %d)" % (ch, ord(ch)))
self.token = ord(ch)
return self.token
# Verilog-A operators: VAMS LRM table 4-1
# Arithmetic: + - * / ** %
# Relational: > >= < <=
# Logical: ! && || == !=
# Bitwise: ~ & | ^
# Ternary: ? :
# Not supported in in Verilog-A:
# Concatenation, replication: {} {{}}
# Case: === !==
# Bitwise: ^~ ~^ ~& ~|
# Shifts: << >> <<< >>>