This file is indexed.

/usr/lib/qflow/scripts/spi2xspice.py is in qflow 1.1.58-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/env python3
#
# spi2xspice.py
#
# Simple script to convert a standard-cell SPICE subcircuit (e.g., one created
# by qflow) into a version replacing all the standard cells with XSPICE
# primitives.  This works in conjunction with lib2xspice.py, which converts
# a liberty file for a standard cell set into a set of XSPICE models using
# d_lut, d_genlut, d_dff, and d_dlatch.
#
# Written by Tim Edwards
# efabless, inc. 2017
# May 17, 2017
# This script is in the public domain
#--------------------------------------------------------------------------

import re
import sys
import os

def read_spice_lib(filein, celldefs, debug):
    # Read a spice library of standard cell definitions

    spicedefs = {}

    with open(filein, 'r') as ifile:
        spitext = ifile.read()

    increx = re.compile('^[^\*]*[ \t]*.include[ \t]+([^ \t]+).*$', re.IGNORECASE)
    subrex  = re.compile('^[^\*]*[ \t]*.subckt[ \t]+([^ \t]+)(.*)$', re.IGNORECASE)
    endsrex = re.compile('^[^\*]*[ \t]*.ends.*$', re.IGNORECASE)
    comrex  = re.compile('^[\*]+.*$', re.IGNORECASE)

    # Merge continuation lines in input
    spilines = spitext.replace('\n+', ' ').splitlines()
    if debug:
        print("Reading spice file, " + str(len(spilines)) + " lines.")

    insub = False
    for line in spilines:

        # All comment lines are ignored
        cmatch = comrex.match(line)
        if cmatch:
            continue

        imatch = increx.match(line)
        if imatch:
            # Check if filename needs same prefix as current file
            if not os.path.exists(imatch.group(1)):
                prefix = os.path.split(filein)[0]
                incfile = prefix + '/' + imatch.group(1)
            else:
                incfile = imatch.group(1)
            read_spice_lib(incfile, celldefs, debug)
            continue

        ematch = endsrex.match(line)
        if ematch:
            if insub:
                insub = False
            else:
                print("Error: .ends outside of a subcircuit")
            continue

        if not insub:
            lmatch = subrex.match(line)
            if lmatch:
                subname = lmatch.group(1)
                if subname in celldefs:
                    if debug:
                        print("Found subcircuit " + subname)
                    # Read information on spice port order into celldefs record
                    # Because line extensions have been handled, all information
                    # is on the first line.
                    cellrec = celldefs[subname]
                    cellrec['spicepins'] = lmatch.group(2).split()

                # Read to the ".ends" statement.
                insub = True

def write_models(cellsused, celldefs, ofile):
    # Write the .model statement for all cells used

    imprex = re.compile('([10\)])[ \t]+([10\(])')
    primerex = re.compile('([10\)])[ \t]*\'')
    for cellname in cellsused:
        cellrec = celldefs[cellname]
        if len(cellrec['function']) > 0:
            print('* ' + cellname + ' ' + cellrec['function'][0], file=ofile)
        else:
            print('* ' + cellname + ' (no function)', file=ofile)
        if cellrec['type'] == 'flop':
            continue
        elif cellrec['type'] == 'latch':
            continue
        elif cellrec['nin'] == 0:
            continue
        else:
            tabstr = ''
            nout = cellrec['nout']
            nin = cellrec['nin']
            for k in range(0, nout):
                # Handle tristate functions
                # If triidx < nin then triidx, tripin, and tripos are all valid
                if 'tristate' in cellrec:
                    trirec = cellrec['tristate']
                    if trirec[0] == '~':
                        tripos = False
                        tripin = trirec[1:]
                    else:
                        tripos = True
                        tripin = trirec
                    for triidx in range(0, nin):
                        if cellrec['inputs'][triidx] == tripin:
                           break
                else:
                    triidx = nin

                pstring = parse_pin(cellrec['function'][k])
                nvals = 2**nin
                for i in range(0, nvals):
                    binstring = '{0:{fill}{width}b}'.format(i, fill='0', width=nin)

                    psubs = pstring
                    for j in range(0, nin):
                        bchar = cellrec['inputs'][nin - j - 1]
                        bval = binstring[j]
                        psubs = psubs.replace(bchar, bval)

                    # Handle the awkward syntax where, e.g., (A B) means (A & B)
                    psubs = imprex.sub('\g<1>&\g<2>', psubs)

                    try:
                        tval = eval('(' + psubs + ')&1')
                    except (SyntaxError, NameError):
                        tabstr = ''
                        print("Could not evaluate function " + cellrec['function'][k])
                        break

                    if tval:
                        bitstr = '1'
                    else:
                        bitstr = '0'

                    if triidx < nin:
                        if binstring[triidx] == '1' and tripos == True:
                            bitstr = 'Z'
                        elif binstring[triidx] == '0' and tripos == False:
                            bitstr = 'Z'

                    tabstr += bitstr

            if tabstr != '':
                if nout == 1:
                    # General n-input LUT model
                    print('.model d_lut_' + cellname + ' d_lut (rise_delay=1n fall_delay=1n input_load=10f', file=ofile)
                    print('+ table_values "' + tabstr + '")', file=ofile)
                    if debug:
                        print('Cell ' + cellname + ' has table ' + tabstr)
                else:
                    # Even more general n-input, m-output LUT model
                    idelstr = ('2n ' * nin).strip() 
                    ilodstr = ('1.0p ' * nin).strip() 
                    odelstr = ('50n ' * nout).strip() 
                            
                    print('.model d_genlut_' + cellname + ' d_genlut (', file=ofile)
                    print('+ rise_delay=[' + odelstr + ']', file=ofile)
                    print('+ fall_delay=[' + odelstr + ']', file=ofile)
                    print('+ input_load=[' + ilodstr + ']', file=ofile)
                    print('+ input_delay=[' + idelstr + ']', file=ofile)
                    print('+ table_values "' + tabstr + '")', file=ofile)
            else:
                print('No output for ' + cellname)

def read_spice(filein, fileout, celldefs, debug, modelfile):
    # Read a top-level SPICE file with a digital standard cell subcircuit, and
    # write it back out as a subcircuit of XSPICE models and calls with
    # appropriate A-to-D and D-to-A bridges.

    # If 'modelfile' is given, then do not write out model lines
    # for the digital cells, but just include the modelfile at top.

    with open(filein, 'r') as ifile:
        spitext = ifile.read()

    increx = re.compile('^[^\*]*[ \t]*.include[ \t]+([^ \t]+).*$', re.IGNORECASE)
    subrex = re.compile('^[^\*]*[ \t]*.subckt[ \t]+([^ \t]+)(.*)$', re.IGNORECASE)
    xrex   = re.compile('^[ \t]*X([^ \t]+)(.*)$', re.IGNORECASE)
    comrex = re.compile('^[\*]+.*$', re.IGNORECASE)
    endsrex = re.compile('^[^\*]*[ \t]*.ends.*$', re.IGNORECASE)

    # Merge continuation lines in input
    spilines = spitext.replace('\n+', ' ').splitlines()
    if debug:
        print("Reading spice file, " + str(len(spilines)) + " lines.")

    # Get expected name of subcircuit from filename
    fileroot = os.path.split(filein)[1]
    subname = os.path.splitext(fileroot)[0]

    cellsused = []

    print("Writing xspice file")
    with open(fileout, 'w') as ofile:
        print("* XSpice netlist created from SPICE and liberty sources by spi2xspice.py", file=ofile)
        echoout = False
        lineno = 0
        for line in spilines:
            lineno += 1

            # Substitute for all characters "<" and ">"
            line = line.replace('<', '_').replace('>', '_')

            # All comment lines go to the output
            cmatch = comrex.match(line)
            if cmatch:
                print(line, file=ofile)
                continue

            # If there is an include line, parse it and read the
            # library cells from that include file.
            imatch = increx.match(line)
            if imatch:
                read_spice_lib(imatch.group(1), celldefs, debug) 
                continue

            xmatch = xrex.match(line)
            if xmatch:
                # Replace subcircuit call with xspice call
                instname = xmatch.group(1)
                conns = xmatch.group(2).split()
                pins = conns[0:-1]
                cellname = conns[-1]

                if cellname not in celldefs:
                    print("Could not find cellname " + cellname + " from subcircuit line " + str(lineno))
                    continue

                if cellname not in cellsused:
                    cellsused.append(cellname)

                cellrec = celldefs[cellname]
                # Tricky!  For each pin, find the corresponding subcircuit
                # pin name.  Then look up that pin name in the cell record
                # and find if it is an input or an output.  Then assign
                # the pin direction to the connecting net.  Then compile
                # the list of input and output nets based on the XSPICE
                # model's port order.

                if not 'spicepins' in cellrec:
                    print('Cell ' + cellname + ' does not have SPICE pin order defined!')
                    continue

                # Print the record.  Special handling for flops and latches.
                if cellrec['type'] == 'flop':

                    dclk = 'NULL'
                    ddata = 'NULL'
                    dreset = 'NULL'
                    dset = 'NULL'
                    dq = 'NULL'
                    dqbar = 'NULL'

                    if 'clock' in cellrec:
                        clkpin = cellrec['clock']
                        if clkpin[0] == '~':
                            subpin = clkpin[1:]
                        else:
                            subpin = clkpin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if clkpin[0] == '~':
                            dclk = '~' + pins[i]
                        else:
                            dclk = pins[i]

                    if 'data' in cellrec:
                        datapin = cellrec['data']
                        if datapin[0] == '~':
                            subpin = datapin[1:]
                        else:
                            subpin = datapin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if datapin[0] == '~':
                            ddata = '~' + pins[i]
                        else:
                            ddata = pins[i]

                    if 'set' in cellrec:
                        setpin = cellrec['set']
                        if setpin[0] == '~':
                            subpin = setpin[1:]
                        else:
                            subpin = setpin
                        if debug:
                            print("flop setpin = " + setpin + " subpin = " + subpin)
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if setpin[0] == '~':
                            dset = '~' + pins[i]
                        else:
                            dset = pins[i]

                    if 'reset' in cellrec:
                        resetpin = cellrec['reset']
                        if resetpin[0] == '~':
                            subpin = resetpin[1:]
                        else:
                            subpin = resetpin
                        if debug:
                            print("flop resetpin = " + resetpin + " subpin = " + subpin)
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if resetpin[0] == '~':
                            dreset = '~' + pins[i]
                        else:
                            dreset = pins[i]

                    for subpin in cellrec['outputs']:
                        subidx = cellrec['outputs'].index(subpin)
                        function = cellrec['function'][subidx]
                        if subpin in cellrec['spicepins']:
                            i = cellrec['spicepins'].index(subpin)
                            if pins[i] in pindefs:
                                pindefs[pins[i]] = 'output'
                            if 'funcneg' in cellrec:
                                if cellrec['funcneg'] == function:
                                    dqbar = pins[i]
                            if 'funcpos' in cellrec:
                                if cellrec['funcpos'] == function:
                                    dq = pins[i]

                    print('A' + instname + ' ' + ddata + ' ' + dclk + ' ' + dset + ' ' + dreset + ' ' + dq + ' ' + dqbar + ' ddflop', file=ofile)

                elif cellrec['type'] == 'latch':

                    dena   = 'NULL'
                    ddata  = 'NULL'
                    dreset = 'NULL'
                    dset   = 'NULL'
                    dq     = 'NULL'
                    dqbar  = 'NULL'

                    if 'enable' in cellrec:
                        enapin = cellrec['enable']
                        if enapin[0] == '~':
                            subpin = enapin[1:]
                        else:
                            subpin = enapin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if enapin[0] == '~':
                            dena = '~' + pins[i]
                        else:
                            dena = pins[i]

                    if 'data' in cellrec:
                        datapin = cellrec['data']
                        if datapin[0] == '~':
                            subpin = datapin[1:]
                        else:
                            subpin = datapin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if datapin[0] == '~':
                            ddata = '~' + pins[i]
                        else:
                            ddata = pins[i]

                    if 'set' in cellrec:
                        setpin = cellrec['set']
                        if setpin[0] == '~':
                            subpin = setpin[1:]
                        else:
                            subpin = setpin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if setpin[0] == '~':
                            dset = '~' + pins[i]
                        else:
                            dset = pins[i]

                    if 'reset' in cellrec:
                        resetpin = cellrec['reset']
                        if resetpin[0] == '~':
                            subpin = resetpin[1:]
                        else:
                            subpin = resetpin
                        i = cellrec['spicepins'].index(subpin)
                        if pins[i] in pindefs:
                            pindefs[pins[i]] = 'input'
                        if resetpin[0] == '~':
                            dreset = '~' + pins[i]
                        else:
                            dreset = pins[i]

                    for subpin in cellrec['outputs']:
                        subidx = cellrec['outputs'].index(subpin)
                        function = cellrec['function'][subidx]
                        if subpin in cellrec['spicepins']:
                            i = cellrec['spicepins'].index(subpin)
                            if pins[i] in pindefs:
                                pindefs[pins[i]] = 'output'
                            if 'funcneg' in cellrec:
                                if cellrec['funcneg'] == function:
                                    dqbar = pins[i]
                            if 'funcpos' in cellrec:
                                if cellrec['funcpos'] == function:
                                    dq = pins[i]

                    print('A' + instname + ' ' + ddata + ' ' + dena + ' ' + dset + ' ' + dreset + ' ' + dq + ' ' + dqbar + ' dlatch', file=ofile)

                else:
                    inlist = []
                    outlist = []
                    for subpin in cellrec['inputs']:
                        if subpin in cellrec['spicepins']:
                            i = cellrec['spicepins'].index(subpin)
                            # "pins[i]" is the name of the connecting net on the top level
                            inlist.append(pins[i])
                            if pins[i] in pindefs:
                                pindefs[pins[i]] = 'input'

                    for subpin in cellrec['outputs']:
                        if subpin in cellrec['spicepins']:
                            i = cellrec['spicepins'].index(subpin)
                            # "pins[i]" is the name of the connecting net on the top level
                            outlist.append(pins[i])
                            if pins[i] in pindefs:
                                pindefs[pins[i]] = 'output'

                    intext = ' '.join(inlist)
                    outtext = ' '.join(outlist)

                    if debug:
                        print("Instance = " + instname + "; inputs = " + intext + "; outputs = " + outtext)

                    if len(inlist) == 0:
                        if cellrec['function'] == '1':
                            print('A' + instname + ' ' + outtext + ' done', file=ofile)
                        elif cellrec['function'] == '0':
                            print('A' + instname + ' ' + outtext + ' dzero', file=ofile)
                        else:
                            print("Cell " + cellname + " has no inputs and no constant function.")
                    elif len(outlist) == 1:
                        print('A' + instname + ' [' + intext + '] ' + outtext + ' d_lut_' + cellname, file=ofile)
                    else:
                        print('A' + instname + ' [' + intext + '] [' + outtext + '] d_genlut_' + cellname, file=ofile)

                continue

            lmatch = subrex.match(line)
            if lmatch:
                # To do:  Maybe handle the difference between subcircuit and file name
                # better?  For now, just take the first subcircuit found and run with it.
                if lmatch.group(1) != subname:
                    subname = lmatch.group(1)

                if lmatch.group(1) == subname:
                    echoout = False
                    if debug:
                        print("Found subcircuit " + subname)
                    # Prepend all signal names with "a_"
                    pins = lmatch.group(2).split()
                    pindefs = {}
                    # Use pindefs dict to track which pins are input and output
                    for pin in pins:
                        pindefs[pin] = 'unknown'

                    # Write modified .subckt line
                    if debug:
                        print("Rewriting subcircuit " + subname)
                    print(".subckt " + subname, end='', file=ofile)
                    for pin in pins:
                        print(' a_' + pin, end='', file=ofile)
                    print('', file=ofile)
 
                else:
                    print('Unexpected subcircuit ' + lmatch.group(1) + ' found in netlist.')
                    echoout = True

            ematch = endsrex.match(line)
            if ematch:
                if not echoout:
                    # Write A-to-D and D-to-A bridge models
                    print("", file=ofile)
                    if modelfile != '':
                        print(".include " + modelfile, file=ofile)
                    else:
                        print(".model todig_3v adc_bridge(in_high=2.0 in_low=1.0 rise_delay=10n fall_delay=10n)", file=ofile)
                        print(".model toana_3v dac_bridge(out_high=3.0 out_low=0.0)", file=ofile)
                        print("", file=ofile)

                        # Write d_dff, d_dlatch, d_pullup, and d_pulldown models
                        print(".model ddflop d_dff(ic=0 rise_delay=1n fall_delay=1n)", file=ofile)
                        print(".model dzero d_pulldown(load=1p)", file=ofile)
                        print(".model done d_pullup(load=1p)", file=ofile)
                        print("", file=ofile)

                    # Write A-to-D and D-to-A bridges
                    inum = 0
                    onum = 0
                    for pinname in pindefs:
                        if pindefs[pinname] == 'input':
                            inum += 1
                            print("AA2D" + str(inum) + " [a_" + pinname + "] [" + pinname + "] todig_3v", file=ofile)
                        elif pindefs[pinname] == 'output':
                            onum += 1
                            print("AD2A" + str(onum) + " [" + pinname + "] [a_" + pinname + "] toana_3v", file=ofile)
                    print("", file=ofile)

                echoout =  True

            if echoout:
                print(line, file=ofile)

        # At the end, write all of the LUT-based digital models.
        if modelfile == '':
            print("", file=ofile)
            write_models(cellsused, celldefs, ofile)
  
        print(".end", file=ofile)

def write_lib(fileout, celldefs, debug):
    # Write a library file containing the models of all of the cells in the
    # liberty file, which can then be included in other xspice simulatable
    # netlists.

    print("Writing xspice model library")
    with open(fileout, 'w') as ofile:
        print("* XSpice library created from liberty sources by spi2xspice.py", file=ofile)
        echoout = False

        print("", file=ofile)
        print(".model todig_3v adc_bridge(in_high=2.0 in_low=1.0 rise_delay=10n fall_delay=10n)", file=ofile)
        print(".model toana_3v dac_bridge(out_high=3.0 out_low=0.0)", file=ofile)
        print("", file=ofile)

        # Write d_dff, d_dlatch, d_pullup, and d_pulldown models
        print(".model ddflop d_dff(ic=0 rise_delay=1n fall_delay=1n)", file=ofile)
        print(".model dzero d_pulldown(load=1p)", file=ofile)
        print(".model done d_pullup(load=1p)", file=ofile)

        cellsused = []
        for cell in celldefs:
            cellsused.append(cell)

        # At the end, write all of the LUT-based digital models.
        print("", file=ofile)
        write_models(cellsused, celldefs, ofile)
        print(".end", file=ofile)

def parse_pin(function):
    # Handle n' as way of expressing ~n or !n
    primerex = re.compile('([^ \t]+)[ \t]*\'')
    outparenrex = re.compile('^[ \t]*\([ \t]*(.+)[ \t]*\)[ \t]*$')
    parenrex = re.compile('\([ \t]*([^ \t\)|&~^]+)[ \t]*\)')
    pstring = function.strip('"').strip()
    pstring = pstring.replace('*', '&').replace('+', '|').replace('!', '~')
    pstring = outparenrex.sub('\g<1>', pstring)
    pstring = parenrex.sub('\g<1>', pstring)
    pstring = primerex.sub('~\g<1>', pstring)
    return pstring

def read_liberty(filein, debug):
    celldefs = {}
    cellrex  = re.compile('[ \t]*cell[ \t]*\(([^)]+)\)')
    pinrex   = re.compile('[ \t]*pin[ \t]*\(([^)]+)\)')
    lat1rex  = re.compile('[ \t]*latch[ \t]*\(([^)]+)\)')
    lat2rex  = re.compile('[ \t]*latch[ \t]*\(([^, \t]+)[ \t]*,[ \t]*([^),]+)\)')
    ff1rex   = re.compile('[ \t]*ff[ \t]*\(([^)]+)\)')
    ff2rex   = re.compile('[ \t]*ff[ \t]*\(([^, \t]+)[ \t]*,[ \t]*([^),]+)\)')
    staterex = re.compile('[ \t]*next_state[ \t]*:[ \t]*([^;]+);')
    clockrex = re.compile('[ \t]*clocked_on[ \t]*:[ \t]*([^;]+);')
    setrex   = re.compile('[ \t]*preset[ \t]*:[ \t]*([^;]+);')
    resetrex = re.compile('[ \t]*clear[ \t]*:[ \t]*([^;]+);')
    datarex  = re.compile('[ \t]*data_in[ \t]*:[ \t]*([^;]+);')
    enarex   = re.compile('[ \t]*enable[ \t]*:[ \t]*([^;]+);')
    trirex   = re.compile('[ \t]*three_state[ \t]*:[ \t]*([^;]+);')
    funcrex  = re.compile('[ \t]*function[ \t]*:[ \t]*\"?[ \t]*([^"]+)[ \t]*\"?')
    with open(filein, 'r') as ifile:
        lines = ifile.readlines()
        if debug:
            print("Reading liberty file, " + str(len(lines)) + " lines.")
        for line in lines:
            lmatch = cellrex.match(line)
            if lmatch:
                cellname = lmatch.group(1)
                if debug:
                    print("Found cell " + cellname)
                cellrec = {}
                cellrec['inputs'] = []
                cellrec['outputs'] = []
                cellrec['nin'] = 0
                cellrec['nout'] = 0
                cellrec['function'] = []
                # NOTE:  average rise and fall times need to be
                # averaged from the data, to get a general relation
                # between timing and drive strength.
                cellrec['rise'] = 1.0
                cellrec['fall'] = 1.0
                cellrec['type'] = 'comb'
                celldefs[cellname] = cellrec
                continue
                
            pmatch = pinrex.match(line)
            if pmatch:
                pinname = pmatch.group(1)
                if debug:
                    print("Found input pin " + pinname)
                cellrec['inputs'].append(pinname)
                cellrec['nin'] += 1
                continue

            lmatch = lat2rex.match(line)
            if lmatch:
                if debug:
                    print("Found latch");
                cellrec['type'] = 'latch'
                cellrec['funcpos'] = lmatch.group(1)
                cellrec['funcneg'] = lmatch.group(2)
                continue

            lmatch = lat2rex.match(line)
            if lmatch:
                if debug:
                    print("Found latch");
                cellrec['type'] = 'latch'
                cellrec['funcpos'] = lmatch.group(1)
                continue

            rmatch = ff2rex.match(line)
            if rmatch:
                if debug:
                    print("Found flop");
                cellrec['type'] = 'flop'
                cellrec['funcpos'] = rmatch.group(1)
                cellrec['funcneg'] = rmatch.group(2)
                continue

            rmatch = ff1rex.match(line)
            if rmatch:
                if debug:
                    print("Found flop");
                cellrec['type'] = 'flop'
                cellrec['funcpos'] = rmatch.group(1)
                continue

            fmatch = funcrex.match(line)
            if fmatch:
                function = fmatch.group(1)
                if debug:
                    print("Found function " + function + " and output pin " + pinname)
                # If pin has a function, it's an output, not an input,
                # so add it to the outputs list and remove it from the
                # inputs list.
                cellrec['outputs'].append(pinname)
                cellrec['nout'] += 1
                cellrec['inputs'].remove(pinname)
                cellrec['nin'] -= 1
                cellrec['function'].append(function)
                continue

            smatch = staterex.match(line)
            if smatch:
                if debug:
                    print('Found data input')
                cellrec['data'] = parse_pin(smatch.group(1))
                continue

            cmatch = clockrex.match(line)
            if cmatch:
                if debug:
                    print('Found clock input')
                cellrec['clock'] = parse_pin(cmatch.group(1))
                continue

            smatch = setrex.match(line)
            if smatch:
                if debug:
                    print('Found set input ' + smatch.group(1))
                cellrec['set'] = parse_pin(smatch.group(1))
                continue

            rmatch = resetrex.match(line)
            if rmatch:
                if debug:
                    print('Found reset input ' + rmatch.group(1))
                cellrec['reset'] = parse_pin(rmatch.group(1))
                continue

            dmatch = datarex.match(line)
            if dmatch:
                if debug:
                    print('Found data input')
                cellrec['data'] = parse_pin(dmatch.group(1))
                continue

            ematch = enarex.match(line)
            if ematch:
                if debug:
                    print('Found enable input')
                cellrec['enable'] = parse_pin(ematch.group(1))
                continue

            tmatch = trirex.match(line)
            if tmatch:
                if debug:
                    print('Found tristate output')
                cellrec['tristate'] = parse_pin(tmatch.group(1))
                continue

    return celldefs


if __name__ == '__main__':

    options = []
    arguments = []
    for item in sys.argv[1:]:
        if item.find('-', 0) == 0:
            options.append(item)
        else:
            arguments.append(item)

    if '-debug' in options:
        debug = True
    else:
        debug = False

    if len(arguments) >= 3:
        print("Reading liberty netlist " + arguments[0])
        print("Reading spice netlist " + arguments[1])
        print("Writing xspice netlist " + arguments[2])
        celldefs = read_liberty(arguments[0], debug)
        if len(arguments) >= 4:
            modelfile = arguments[3]
        else:
            modelfile = ''
        read_spice(arguments[1], arguments[2], celldefs, debug, modelfile)
        print("Done.")
    elif len(arguments) == 2:
        # Library-only option
        print("Reading liberty netlist " + arguments[0])
        print("Writing xspice model library " + arguments[1])
        celldefs = read_liberty(arguments[0], debug)
        write_lib(arguments[1], celldefs, debug)
        print("Done.")
    else:
        print("Usage:")
        print("spi2xspice.py <liberty file> <input spice> <output spice> [<xspice lib>]")
        print("spi2xspice.py <liberty file> <output xspice lib>")