-
Notifications
You must be signed in to change notification settings - Fork 1
/
data.py
633 lines (428 loc) · 13.6 KB
/
data.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
"""
# Netlist Data Model
All elements in the netlist-internal "IR",
primarily in the form of dataclasses.
"""
# Std-Lib Imports
from enum import Enum
from pathlib import Path
from dataclasses import field
from typing import Optional, Union, List, Tuple, Generic, TypeVar
# PyPi Imports
from pydantic.dataclasses import dataclass
from pydantic.generics import GenericModel
class NetlistParseError(Exception):
"""Netlist Parse Error"""
@staticmethod
def throw(*args, **kwargs):
"""Exception-raising debug wrapper. Breakpoint to catch `NetlistParseError`s."""
raise NetlistParseError(*args, **kwargs)
class NetlistDialects(Enum):
"""Enumerated, Supported Netlist Dialects"""
SPECTRE = "spectre"
SPECTRE_SPICE = "spectre_spice"
SPICE = "spice"
HSPICE = "hspice"
NGSPICE = "ngspice"
XYCE = "xyce"
CDL = "cdl"
@staticmethod
def get(spec: "NetlistFormatSpec") -> "NetlistDialects":
"""Get the format specified by `spec`, in either enum or string terms.
Only does real work in the case when `spec` is a string, otherwise returns it unchanged."""
if isinstance(spec, (NetlistDialects, str)):
return NetlistDialects(spec)
raise TypeError
# Type-alias for specifying format, either in enum or string terms
NetlistFormatSpec = Union[NetlistDialects, str]
def to_json(arg) -> str:
"""Dump any `pydantic.dataclass` or simple combination thereof to JSON string."""
import json
from pydantic.json import pydantic_encoder
return json.dumps(arg, indent=2, default=pydantic_encoder)
@dataclass
class SourceInfo:
"""Parser Source Information"""
line: int # Source-File Line Number
dialect: "NetlistDialects" # Netlist Dialect
# Keep a list of datatypes defined here,
# primarily so that we can update their forward-references at the end of this module.
datatypes = [SourceInfo]
def datatype(cls: type) -> type:
"""Register a class as a datatype."""
# Add an `Optional[SourceInfo]` field to the class, with a default value of `None`.
# Creates the `__annotations__` field if it does not already exist.
anno = getattr(cls, "__annotations__", {})
anno["source_info"] = Optional[SourceInfo]
cls.__annotations__ = anno
cls.source_info = None
# Convert it to a `pydantic.dataclasses.dataclass`
cls = dataclass(cls)
# And add it to the list of datatypes
datatypes.append(cls)
return cls
@datatype
class Ident:
"""Identifier"""
name: str
class RefType(Enum):
"""External Reference Types Enumeration
Store on each `ExternalRef` to note which types would be valid in context."""
SUBCKT = "SUBCKT" # Sub-circuit definition
MODEL = "MODEL" # Model definition
PARAM = "PARAM" # Parameter reference
FUNCTION = "FUNCTION" # Function definition
FILEPATH = "FILEPATH" # File-system path, e.g. in `Include`s not parsed
def __repr__(self):
return f"RefType.{self.name}"
@datatype
class ExternalRef:
"""# External Reference
Name-based reference to something outside the netlist-program."""
# Referred-to identifier
ident: Ident
# List of types which this can validly refer to
types: List[RefType] = field(default_factory=list)
# Generic type of "the thing that a `Ref` refers to"
Referent = TypeVar("Referent")
class Ref(GenericModel, Generic[Referent]):
"""# Reference to another Netlist object
Intially an identifier, then in later stages resolved to a generic `Referent`."""
# Referred-to identifier
ident: Ident
# Resolved referent, or `None` if unresolved.
resolved: Optional[Union[Referent, ExternalRef]] = None
@datatype
class HierPath:
"""Hierarchical Path Identifier"""
path: List[Ident] # FIXME: Ref?
@datatype
class ParamDecl:
"""Parameter Declaration
Includes Optional Distribution Information"""
name: Ident
default: Optional["Expr"]
distr: Optional[str] = None
@datatype
class ParamDecls:
"""Parameter Declarations,
as via the `param` keywords."""
params: List[ParamDecl]
@datatype
class ParamVal:
"""Parameter Value-Set"""
name: Ident
val: "Expr"
@datatype
class QuotedString:
"""Quoted String Value"""
txt: str
# Simulation Options can take on the values of expressions, e.g. parameter combinations,
# and those of quoted strings, often for file-path.
OptionVal = Union[QuotedString, "Expr"]
@datatype
class Option:
"""Simulation Option"""
name: Ident # Option Name
val: OptionVal # Option Value
@datatype
class Options:
"""Simulation Options"""
name: Optional[Ident] # Option Name. FIXME: could this be removed
vals: List[Option] # List of [`Option`]s
@datatype
class StartSubckt:
"""Start of a Subckt / Module Definition"""
name: Ident # Module/ Subcircuit Name
ports: List[Ident] # Port List
params: List[ParamDecl] # Parameter Declarations
@datatype
class EndSubckt:
"""End of a Subckt / Module Definition"""
name: Optional[Ident]
@datatype
class SubcktDef:
"""Sub-Circuit / Module Definition"""
name: Ident # Module/ Subcircuit Name
ports: List[Ident] # Port List
params: List[ParamDecl] # Parameter Declarations
entries: List["Entry"]
@datatype
class ModelDef:
"""Model Definition"""
name: Ident # Model Name
mtype: Ident # Model Type
args: List[Ident] # Positional Arguments
params: List[ParamDecl] # Parameter Declarations & Defaults
@datatype
class ModelVariant:
"""Model Variant within a `ModelFamily`"""
model: Ident # Model Family Name
variant: Ident # Variant Name
mtype: Ident # Model Type
args: List[Ident] # Positional Arguments
params: List[ParamDecl] # Parameter Declarations & Defaults
@datatype
class ModelFamily:
"""Model Family
A set of related, identically named models, generally separated by limiting parameters such as {lmin, lmax} or {wmin, wmax}."""
name: Ident # Model Family Name
mtype: Ident # Model Type
variants: List[ModelVariant] # Variants
# The primary `Model` type-union includes both single-variant and multi-variant versions
Model = Union[ModelDef, ModelFamily]
@datatype
class Instance:
"""Subckt / Module Instance"""
name: Ident # Instance Name
module: Ref[Union[SubcktDef, Model]] # Module/ Subcircuit Reference
# Connections, either by-position or by-name
conns: Union[List[Ident], List[Tuple[Ident, Ident]]]
params: List[ParamVal] # Parameter Values
@datatype
class Primitive:
"""
Primitive Instance
Note at parsing-time, before models are sorted out,
it is not always clear what is a port, model name, and parameter value.
Primitives instead store positional and keyword arguments `args` and `kwargs`.
"""
name: Ident
args: List["Expr"]
kwargs: List[ParamVal]
@datatype
class Include:
"""Include (a File) Statement"""
path: Path
@datatype
class AhdlInclude:
"""Analog HDL Include (a File) Statement"""
path: Path
@datatype
class StartLib:
"""Start of a `Library`"""
name: Ident
@datatype
class EndLib:
"""End of a `Library`"""
name: Optional[Ident]
@datatype
class StartLibSection:
"""Start of a `LibrarySection`"""
name: Ident
@datatype
class EndLibSection:
"""End of a `LibrarySection`"""
name: Ident
@datatype
class LibSectionDef:
"""Library Section
A named section of a library, commonly incorporated with a `UseLibSection` or similar."""
name: Ident # Section Name
entries: List["Entry"] # Entry List
@datatype
class StartProtectedSection:
"""Start of a `ProtectedSection`"""
... # Empty
@datatype
class EndProtectedSection:
"""End of a `ProtectedSection`"""
... # Empty
@datatype
class ProtectedSection:
"""Protected Section"""
entries: List["Entry"] # Entry List
@datatype
class Library:
"""Library, as Generated by the Spice `.lib` Definition Card
Includes a list of named `LibSectionDef`s which can be included by their string-name,
as common for "corner" inclusions e.g. `.inc "mylib.sp" "tt"`"""
name: Ident # Library Name
sections: List[LibSectionDef] # Library Sections
@datatype
class UseLibSection:
"""Use a Library"""
path: Path # Library File Path
section: Ident # Section Name
@datatype
class End:
"""Empty class represents `.end` Statements"""
... # Empty
@datatype
class Variation:
"""Single-Parameter Variation Declaration"""
name: Ident # Parameter Name
dist: str # Distribution Name/Type
std: "Expr" # Standard Deviation
@datatype
class StatisticsBlock:
"""Statistical Descriptions"""
process: Optional[List[Variation]]
mismatch: Optional[List[Variation]]
@datatype
class Unknown:
"""Unknown Netlist Statement. Stored as an un-parsed string."""
txt: str
@datatype
class DialectChange:
"""Netlist Dialect Changes, e.g. `simulator lang=xyz`"""
dialect: str
# Union of "flat" statements lacking (substantial) hierarchy
FlatStatement = Union[
Instance,
Primitive,
ParamDecls,
ModelDef,
ModelVariant,
ModelFamily,
DialectChange,
"FunctionDef",
Unknown,
Options,
Include,
AhdlInclude,
UseLibSection,
StatisticsBlock,
]
# Statements which indicate the beginning and end of hierarchical elements,
# and ultimately disappear into the structured AST
DelimStatement = Union[
StartLib,
EndLib,
StartLibSection,
EndLibSection,
End,
]
# Statements
# The union of types which can appear in first-pass parsing netlist
Statement = Union[FlatStatement, DelimStatement]
# Entries - the union of types which serve as "high-level" AST nodes,
# i.e. those which can be the direct children of a `SourceFile`.
Entry = Union[FlatStatement, SubcktDef, Library, LibSectionDef, End]
@datatype
class SourceFile:
path: Path # Source File Path
contents: List[Entry] # Statements and their associated SourceInfo
@datatype
class Program:
"""
# Multi-File "Netlist Program"
The name of this type is a bit misleading, but borrowed from more typical compiler-parsers.
Spice-culture generally lacks a term for "the totality of a simulator invocation input",
or even "a pile of source-files to be used together".
So, `Program` it is.
"""
files: List[SourceFile] # List of Source-File Contents
@datatype
class Int:
"""Integer Number"""
val: int
@datatype
class Float:
"""Floating Point Number"""
val: float
@datatype
class MetricNum:
"""Number with Metric Suffix"""
val: str # No conversion, just stored as string for now
class ArgType(Enum):
"""Enumerated Supported Types for Function Arguments and Return Values"""
REAL = "REAL"
UNKNOWN = "UNKNOWN"
def __repr__(self):
return f"ArgType.{self.name}"
@datatype
class TypedArg:
"""Typed Function Argument"""
tp: ArgType # Argument Type
name: Ident # Argument Name
@datatype
class Return:
"""Function Return Node"""
val: "Expr"
# Types which can be used inside a function definition.
# Will of course grow, in time.
FuncStatement = Union[Return]
@datatype
class FunctionDef:
"""Function Definition"""
name: Ident # Function Name
rtype: ArgType # Return Type
args: List[TypedArg] # Argument List
stmts: List[FuncStatement] # Function Body/ Statements
@datatype
class Call:
"""
Function Call Node
All valid parameter-generating function calls return a single value,
usable in a mathematical expression (`Expr`) context.
All arguments are provided by position and stored in a List.
All arguments must also be resolvable as mathematical expressions.
Examples:
`sqrt(2)` => Call(func=Ident("sqrt"), args=([Int(2)]),)
"""
func: Ref[FunctionDef] # Function Name
args: List["Expr"] # Arguments List
class UnaryOperator(Enum):
"""Enumerated, Supported Unary Operators
Values generally equal their string-format equivalents."""
PLUS = "+"
NEG = "-"
def __repr__(self):
return f"UnaryOperator.{self.name}"
@datatype
class UnaryOp:
"""Unary Operation"""
tp: UnaryOperator # Operator Type
targ: "Expr" # Target Expression
class BinaryOperator(Enum):
"""Enumerated, Supported Binary Operators
Values generally equal their string-format equivalents."""
ADD = "+"
SUB = "-"
MUL = "*"
DIV = "/"
POW = "^" # Note there is some divergence between caret and double-star here.
GT = ">"
LT = "<"
GE = ">="
LE = "<="
def __repr__(self):
return f"BinaryOperator.{self.name}"
@datatype
class BinaryOp:
"""Binary Operation"""
tp: BinaryOperator # Enumerated Operator Type
left: "Expr" # Left Operand Expression
right: "Expr" # Right Operand Expression
@datatype
class TernOp:
"""Ternary Operation"""
cond: "Expr" # Condition Expression
if_true: "Expr" # Value if `cond` is True
if_false: "Expr" # Value if `cond` is False
# Expression Union
# Everything which can be used as a mathematical expression,
# and ultimately resolves to a scalar value at runtime.
Expr = Union[UnaryOp, BinaryOp, TernOp, Int, Float, MetricNum, Ref, Call]
# Update all the forward type-references
for tp in datatypes:
tp.__pydantic_model__.update_forward_refs()
# And solely export the defined datatypes
# (at least with star-imports, which are hard to avoid using with all these types)
__all__ = [tp.__name__ for tp in datatypes] + [
"NetlistDialects",
"NetlistParseError",
"BinaryOperator",
"UnaryOperator",
"Expr",
"Entry",
"Ref",
"RefType",
"ExternalRef",
"OptionVal",
"ArgType",
"Model",
"Statement",
"to_json",
]