liberty-db 0.16.4

A fully defined liberty (std. cells in VLSI) data structure, efficient parser & formatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
use crate::{
  Ctx,
  ast::{
    self, Attributes, ComplexAttri, ComplexParseError, GroupComments, GroupFn, GroupSet,
    ParseScope,
  },
};
#[cfg(feature = "lut_template")]
use alloc::sync::Arc;
use core::fmt::{self, Write};
#[cfg(not(feature = "lut_template"))]
use core::marker::PhantomData;
use strum::{Display, EnumString};

pub trait TableCtx<C: Ctx> {
  /// Comes from one of
  /// + `lu_table_template`
  /// + `power_lut_template`
  /// + `output_current_template`
  #[cfg(feature = "lut_template")]
  fn lut_template(&self) -> &Option<Arc<TableTemple<C>>>;
  #[cfg(feature = "lut_template")]
  fn set_lut_template(&mut self, template: Option<&Arc<TableTemple<C>>>);
}

pub trait CompactTableCtx<C: Ctx> {
  #[cfg(feature = "lut_template")]
  fn compact_lut_template(&self) -> &Option<Arc<CompactLutTemplate<C>>>;
  #[cfg(feature = "lut_template")]
  fn set_compact_lut_template(&mut self, template: Option<&Arc<CompactLutTemplate<C>>>);
}

macro_rules! use_common_template {
  ($table:tt, $scope:tt) => {
    #[cfg(feature = "lut_template")]
    crate::table::TableCtx::set_lut_template(
      &mut $table.extra_ctx,
      $scope.lu_table_template.get(&$table.name),
    )
  };
}
pub(crate) use use_common_template;

macro_rules! use_power_template {
  ($table:tt, $scope:tt) => {
    #[cfg(feature = "lut_template")]
    crate::table::TableCtx::set_lut_template(
      &mut $table.extra_ctx,
      $scope.power_lut_template.get(&$table.name),
    )
  };
}
pub(crate) use use_power_template;

macro_rules! use_current_template {
  ($table:tt, $scope:tt) => {
    #[cfg(feature = "lut_template")]
    crate::table::TableCtx::set_lut_template(
      &mut $table.extra_ctx,
      $scope.output_current_template.get(&$table.name),
    )
  };
}
pub(crate) use use_current_template;

macro_rules! use_compact_template {
  ($table:tt, $scope:tt) => {
    #[cfg(feature = "lut_template")]
    crate::table::CompactTableCtx::set_compact_lut_template(
      &mut $table.extra_ctx,
      $scope.compact_lut_template.get(&$table.name),
    )
  };
}
pub(crate) use use_compact_template;

#[derive(Clone, Default, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct DefaultTableCtx<C: Ctx> {
  #[cfg(feature = "lut_template")]
  pub lut_template: Option<Arc<TableTemple<C>>>,
  #[cfg(not(feature = "lut_template"))]
  ___p: PhantomData<C::Other>,
}
impl<C: Ctx> TableCtx<C> for DefaultTableCtx<C> {
  #[inline]
  #[cfg(feature = "lut_template")]
  fn lut_template(&self) -> &Option<Arc<TableTemple<C>>> {
    &self.lut_template
  }
  #[inline]
  #[cfg(feature = "lut_template")]
  fn set_lut_template(&mut self, template: Option<&Arc<TableTemple<C>>>) {
    self.lut_template = template.cloned();
  }
}
#[derive(Clone, Default, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct DefaultCompactTableCtx<C: Ctx> {
  #[cfg(feature = "lut_template")]
  pub compact_lut_template: Option<Arc<CompactLutTemplate<C>>>,
  #[cfg(not(feature = "lut_template"))]
  ___p: PhantomData<C::Other>,
}
impl<C: Ctx> CompactTableCtx<C> for DefaultCompactTableCtx<C> {
  #[inline]
  #[cfg(feature = "lut_template")]
  fn compact_lut_template(&self) -> &Option<Arc<CompactLutTemplate<C>>> {
    &self.compact_lut_template
  }
  #[inline]
  #[cfg(feature = "lut_template")]
  fn set_compact_lut_template(&mut self, template: Option<&Arc<CompactLutTemplate<C>>>) {
    self.compact_lut_template = template.cloned();
  }
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct TableLookUpMultiSegment<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[id]
  #[liberty(simple)]
  segment: usize,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub index_4: Vec<f64>,
  #[liberty(complex)]
  pub values: Values,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct DriverWaveform<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// The `driver_waveform_name`  string attribute differentiates the driver waveform table
  /// from other driver waveform tables when multiple tables are defined.
  /// The cell-specific, rise-specific, and fall-specific driver waveform usage modeling
  /// depend on this attribute.
  ///
  /// The `driver_waveform_name`  attribute is optional.
  /// You can define a driver waveform table without the attribute, but there can be only one table in a library,
  /// and that table is regarded as the default driver waveform table for all cells in the library.
  /// If more than one table is defined without the attribute, the last table is used.
  /// The other tables are ignored and not stored in the library database file.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=71.24&end=71.31
  /// ">Reference</a>
  #[liberty(simple(type = Option))]
  #[id]
  pub driver_waveform_name: Option<String>,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Other,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub index_4: Vec<f64>,
  #[liberty(complex)]
  pub values: Values,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct TableLookUp2D<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub values: Values,
}

/// The `compact_lut_template`  group is a lookup table template used for compact CCS timing and power modeling.
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=41.20&end=41.21
/// ">Reference</a>
#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CompactLutTemplate<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::CompactTable,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(simple(type = Option))]
  pub base_curves_group: Option<String>,
  /// The only valid values for the `variable_1`  and `variable_2`  attributes are `input_net_transition`  and `total_output_net_capacitance`.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=42.21&end=42.22
  /// ">Reference</a>
  #[liberty(simple(type = Option))]
  pub variable_1: Option<VariableTypeCompactLutTemplateIndex12>,
  /// The `index_1`  and `index_2`  attributes are required.
  /// The `index_1`  and `index_2`  attributes define the
  /// `input_net_transition`  and `total_output_net_capacitance`  values.
  /// The index value for `input_net_transition`  or `total_output_net_capacitance`  
  /// is a floating-point number.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=43.7&end=43.10
  /// ">Reference</a>
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  /// The only valid values for the `variable_1`  and `variable_2`  attributes are `input_net_transition`  and `total_output_net_capacitance`.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=42.21&end=42.22
  /// ">Reference</a>
  #[liberty(simple(type = Option))]
  pub variable_2: Option<VariableTypeCompactLutTemplateIndex12>,
  /// The `index_1`  and `index_2`  attributes are required.
  /// The `index_1`  and `index_2`  attributes define the
  /// `input_net_transition`  and `total_output_net_capacitance`  values.
  /// The index value for `input_net_transition`  or `total_output_net_capacitance`  
  /// is a floating-point number.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=43.7&end=43.10
  /// ">Reference</a>
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  /// The string values in `index_3`  are determined by the `base_curve_type` value
  /// in the `base_curve`  group. When `ccs_timing_half_curve` is the
  /// `base_curve_type`  value, the following six string values (parameters)
  /// should be defined: `init_current`, `peak_current`, `peak_voltage`, `peak_time`, `left_id`, `right_id`;
  /// their order is not fixed.
  #[liberty(simple(type = Option))]
  pub variable_3: Option<VariableTypeCompactLutTemplateIndex3>,
  /// The string values in `index_3`  are determined by the `base_curve_type` value
  /// in the `base_curve`  group. When `ccs_timing_half_curve` is the
  /// `base_curve_type`  value, the following six string values (parameters)
  /// should be defined: `init_current`, `peak_current`, `peak_voltage`, `peak_time`, `left_id`, `right_id`;
  /// their order is not fixed.
  ///
  /// More than six parameters are allowed if a more robust syntax is required
  /// or for circumstances where more parameters are needed to describe the original data.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=43.18+43.22&end=43.21+43.23
  /// ">Reference</a>
  #[liberty(complex)]
  pub index_3: Vec<String>,
}

impl<C: Ctx> GroupFn<C> for CompactLutTemplate<C> {
  #[cfg(feature = "lut_template")]
  fn after_build(&mut self, scope: &mut ast::BuilderScope<C>) {
    self
      .extra_ctx
      .set_compact_lut_template(scope.compact_lut_template.get(&self.name));
  }
}

/// The only valid values for the `variable_1`  and `variable_2`  attributes are `input_net_transition`  and `total_output_net_capacitance`.
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=42.21&end=42.22
/// ">Reference</a>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(strum::Display, strum::EnumString)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum VariableTypeCompactLutTemplateIndex12 {
  #[strum(serialize = "input_net_transition")]
  InputNetTransition,
  #[strum(serialize = "total_output_net_capacitance")]
  TotalOutputNetCapacitance,
}
crate::ast::impl_self_builder!(VariableTypeCompactLutTemplateIndex12);
crate::ast::impl_simple!(VariableTypeCompactLutTemplateIndex12);

/// The only legal string value for the `variable_3`  attribute is `curve_parameters`.
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=42.30&end=42.31
/// ">Reference</a>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(strum::Display, strum::EnumString)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum VariableTypeCompactLutTemplateIndex3 {
  #[strum(serialize = "curve_parameters")]
  CurveParameters,
}
crate::ast::impl_self_builder!(VariableTypeCompactLutTemplateIndex3);
crate::ast::impl_simple!(VariableTypeCompactLutTemplateIndex3);

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct Vector3D<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_1: f64,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_2: f64,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub values: Vec<f64>,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct ReferenceTimeVector3D<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(simple)]
  pub reference_time: f64,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_1: f64,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_2: f64,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub values: Vec<f64>,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct Vector4D<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_1: f64,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_2: f64,
  #[id(into_hash_ord_fn = crate::common::f64_into_hash_ord_fn)]
  #[liberty(complex)]
  pub index_3: f64,
  #[liberty(complex)]
  pub index_4: Vec<f64>,
  #[liberty(complex)]
  pub values: Vec<f64>,
}

/// The `compact_ccs_power` group contains a detailed description for compact CCS
/// power data. The `compact_ccs_power` group includes the following optional attributes:
/// `base_curves_group`, `index_1`, `index_2`, `index_3` and `index_4`. The description for these
/// attributes in the `compact_ccs_power` group is the same as in the `compact_lut_template`
/// group. However, the attributes have a higher priority in the `compact_ccs_power` group.
/// For more information, see `compact_lut_template` Group on page 41.
/// The `index_output` attribute is also optional. It is used only on cross type tables. For
/// more information about the `index_output` attribute, see `index_output` Simple Attribute on
/// page 156.
/// ``` text
/// library (name) {
///   cell(cell_name) {
///     dynamic_current() {
///       switching_group() {
///         pg_current(pg_pin_name) {
///           compact_ccs_power (template_name) {
///             base_curves_group : bc_name;
///             index_output : pin_name;
///             index_1 ("float, ..., float");
///             index_2 ("float, ..., float");
///             index_3 ("float, ..., float");
///             index_4 ("string, ..., string");
///             values ("float | integer, ..., float | integer");
///           } /* end of compact_ccs_power */
///         }
///       }
///     }
///   }
/// }
/// ```
/// Complex Attributes
/// `base_curves_group : bc_name;`
/// `index_output : pin_name;`
/// `index_1 ("float, ..., float");`
/// `index_2 ("float, ..., float");`
/// `index_3 ("float, ..., float");`
/// `index_4 ("string, ..., string");`
/// `values ("float | integer, ..., float | integer");`
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=153.30+154.2&end=153.40+154.25
/// ">Reference</a>
/// <script>
/// IFRAME('https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html');
/// </script>
#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct CompactCcsPower<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::CompactTable,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(simple(type = Option))]
  pub base_curves_group: Option<String>,
  #[liberty(simple(type = Option))]
  pub index_output: Option<String>,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub index_4: Vec<String>,
  /// The values attribute is required in the `compact_ccs_power` group. The data within the
  /// quotation marks (" "), or line, represent the current waveform for one index combination.
  /// Each value is determined by the corresponding curve parameter. In the following line,
  /// "t0, c0, 1, t1, c1, 2, t2, c2, 3, t3, c3, 4, t4, c4"
  /// the size is 14 = 8+3*2. Therefore, the curve parameters are as follows:
  ///
  /// "init_time, init_current, bc_id1, point_time1, point_current1, bc_id2, \
  /// point_time2, point_current2, bc_id3, point_time3, point_current3,
  /// bc_id4,\
  /// end_time, end_current"
  ///
  /// The elements in the values attribute are floating-point numbers for time and current and
  /// integers for the base curve ID. The number of current waveform segments can be different
  /// for each slew and load combination, which means that each line size can be different.
  /// Liberty syntax supports tables with varying sizes, as shown:
  /// ``` text
  /// compact_ccs_power (template_name) {
  ///   ...
  ///   index_1("0.1, 0.2"); /* input_net_transition */
  ///   index_2("1.0, 2.0"); /* total_output_net_capacitance */
  ///   index_3 ("init_time, init_current, bc_id1, point_time1, point_current1, bc_id2, [point_time2, point_current2, bc_id3, ...], end_time, end_current"); /* curve_parameters */
  ///   values ("t0, c0, 1, t1, c1, 2, t2, c2, 3, t3, c3, 4, t4, c4", \ /* segment=4 */
  ///     "t0, c0, 1, t1, c1, 2, t2, c2", \ /* segment=2 */
  ///     "t0, c0, 1, t1, c1, 2, t2, c2, 3, t3, c3", \ /* segment=3 */
  ///     "t0, c0, 1, t1, c1, 2, t2, c2, 3, t3, c3"); /* segment=3 */
  /// }
  /// ```
  ///
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=154.27+155.2&end=154.43+155.12
  /// ">Reference</a>
  #[liberty(complex)]
  pub values: Vec<CcsPowerValue>,
}

#[derive(Debug, Clone)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CcsPowerValue {
  pub init_time: f64,
  pub init_current: f64,
  pub points: Vec<CcsPowerPoint>,
}

#[derive(Debug, Clone, Copy)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CcsPowerPoint {
  pub bc_id: usize,
  pub point_time: f64,
  pub point_current: f64,
}
crate::ast::impl_self_builder!(Vec<CcsPowerValue>);
impl<C: Ctx> ComplexAttri<C> for Vec<CcsPowerValue> {
  #[inline]
  fn parse<'a, I: Iterator<Item = &'a &'a str>>(
    _iter: I,
    _scope: &mut ParseScope<'_>,
  ) -> Result<Self, ComplexParseError> {
    unreachable!()
  }
  #[inline]
  #[expect(clippy::arithmetic_side_effects)]
  fn nom_parse<'a>(
    i: &'a str,
    scope: &mut ParseScope<'_>,
  ) -> ast::ComplexParseRes<'a, Self> {
    match ast::parser::complex_ccs_power_values(i, &mut scope.loc.line_num) {
      Ok((_i, vec)) => {
        let res = vec
          .into_iter()
          .map(|(n, v)| {
            scope.loc.line_num += n;
            v
          })
          .collect();
        Ok((_i, Ok(res)))
      }
      Err(_) => {
        Err(nom::Err::Error(nom::error::Error::new(i, nom::error::ErrorKind::ManyMN)))
      }
    }
  }
  #[inline]
  #[expect(clippy::items_after_statements)]
  fn fmt_self<T: Write, I: ast::Indentation>(
    &self,
    f: &mut ast::CodeFormatter<'_, T, I>,
  ) -> fmt::Result {
    let mut iter = self.iter();
    #[inline]
    fn fmt_point<T: Write, I: ast::Indentation>(
      point: &CcsPowerPoint,
      f: &mut ast::CodeFormatter<'_, T, I>,
    ) -> fmt::Result {
      f.write_num(point.bc_id)?;
      f.write_str(", ")?;
      f.write_num(point.point_time)?;
      f.write_str(", ")?;
      f.write_num(point.point_current)
    }
    #[inline]
    fn fmt_value<T: Write, I: ast::Indentation>(
      value: &CcsPowerValue,
      f: &mut ast::CodeFormatter<'_, T, I>,
    ) -> fmt::Result {
      write!(f, "\"")?;
      f.write_num(value.init_time)?;
      f.write_str(", ")?;
      f.write_num(value.init_current)?;
      if !value.points.is_empty() {
        f.write_str(", ")?;
        ast::join_fmt_no_quote(
          value.points.iter(),
          f,
          |point, ff| fmt_point(point, ff),
          |ff| write!(ff, ", "),
        )?;
      }
      write!(f, "\"")
    }
    if let Some(value) = iter.next() {
      fmt_value(value, f)?;
    }
    while let Some(value) = iter.next() {
      write!(f, ", \\")?;
      f.write_new_line_indentation()?;
      fmt_value(value, f)?;
    }
    Ok(())
  }
}
#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct Vector3DGrpup<C: Ctx> {
  #[liberty(name)]
  #[id]
  pub name: Option<String>,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Other,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(group(type = Set))]
  #[liberty(after_build = use_common_template!)]
  pub vector: GroupSet<Vector3D<C>>,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct ReferenceTimeVector3DGrpup<C: Ctx> {
  #[liberty(name)]
  #[id]
  pub name: Option<String>,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Other,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(group(type = Set))]
  #[liberty(after_build = use_current_template!)]
  pub vector: GroupSet<ReferenceTimeVector3D<C>>,
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct Vector4DGrpup<C: Ctx> {
  #[liberty(name)]
  #[id]
  pub name: Option<String>,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Other,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(group(type = Set))]
  #[liberty(after_build = use_common_template!)]
  pub vector: GroupSet<Vector4D<C>>,
}
impl<C: Ctx> GroupFn<C> for Vector4DGrpup<C> {}
impl<C: Ctx> GroupFn<C> for Vector3DGrpup<C> {}
impl<C: Ctx> GroupFn<C> for Vector3D<C> {}
impl<C: Ctx> GroupFn<C> for Vector4D<C> {}
impl<C: Ctx> GroupFn<C> for ReferenceTimeVector3D<C> {}
impl<C: Ctx> GroupFn<C> for ReferenceTimeVector3DGrpup<C> {}
impl<C: Ctx> GroupFn<C> for CompactCcsPower<C> {}

/// Specify the optional `sigma_type` attribute to define the type of arrival time listed in the
/// `ocv_sigma_cell_rise`, `ocv_sigma_cell_fall`, `ocv_sigma_rise_transition`, and
/// `ocv_sigma_fall_transition` group lookup tables.
#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct OcvSigmaTable<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  /// Specify the optional `sigma_type` attribute to define the type of arrival time listed in the
  /// `ocv_sigma_cell_rise`, `ocv_sigma_cell_fall`, `ocv_sigma_rise_transition`, and
  /// `ocv_sigma_fall_transition` group lookup tables. The values are `early`, `late`, and
  /// `early_and_late`. The default is `early_and_late`.
  ///
  /// You can specify the `sigma_type` attribute in the `ocv_sigma_cell_rise` and
  /// `ocv_sigma_cell_fall` groups.
  ///
  /// ### Syntax
  /// ``` text
  /// sigma_type: early | late | early_and_late;
  /// ```
  /// ### Example
  /// ``` text
  /// sigma_type: early;
  /// ```
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=357.15&end=357.24
  /// ">Reference-Definition</a>
  #[liberty(simple)]
  #[id]
  pub sigma_type: SigmaType,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub values: Values,
}

/// The `compact_ccs_rise`  and `compact_ccs_fall`  groups define the compact CCS timing data in the timing arc.
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=352.40&end=352.41
/// ">Reference-Definition</a>
#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::CompactTable: serde::Serialize + serde::de::DeserializeOwned")]
pub struct CompactCcsTable<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::CompactTable,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(simple)]
  pub base_curves_group: String,
  #[liberty(complex)]
  pub values: Values,
}
impl<C: Ctx> GroupFn<C> for CompactCcsTable<C> {}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Table: serde::Serialize + serde::de::DeserializeOwned")]
pub struct TableLookUp<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Table,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(complex)]
  pub index_1: Vec<f64>,
  #[liberty(complex)]
  pub index_2: Vec<f64>,
  #[liberty(complex)]
  pub index_3: Vec<f64>,
  #[liberty(complex)]
  pub index_4: Vec<f64>,
  #[liberty(complex)]
  pub values: Values,
}
impl<C: Ctx> GroupFn<C> for TableLookUp<C> {
  #[expect(clippy::arithmetic_side_effects)]
  fn before_build(builder: &mut Self::Builder, _: &mut ast::BuilderScope<C>) {
    if builder.values.chunk_size == builder.values.inner.len()
      && builder.values.inner.len() == builder.index_1.len() * builder.index_2.len()
    {
      builder.values.chunk_size = builder.index_2.len();
    }
  }
}
impl<C: Ctx> GroupFn<C> for TableLookUpMultiSegment<C> {
  #[expect(clippy::arithmetic_side_effects)]
  fn before_build(builder: &mut Self::Builder, _: &mut ast::BuilderScope<C>) {
    if builder.values.chunk_size == builder.values.inner.len()
      && builder.values.inner.len() == builder.index_1.len() * builder.index_2.len()
    {
      builder.values.chunk_size = builder.index_2.len();
    }
  }
}
impl<C: Ctx> GroupFn<C> for TableLookUp2D<C> {
  #[expect(clippy::arithmetic_side_effects)]
  fn before_build(builder: &mut Self::Builder, _: &mut ast::BuilderScope<C>) {
    if builder.values.chunk_size == builder.values.inner.len()
      && builder.values.inner.len() == builder.index_1.len() * builder.index_2.len()
    {
      builder.values.chunk_size = builder.index_2.len();
    }
  }
}
impl<C: Ctx> GroupFn<C> for OcvSigmaTable<C> {
  #[expect(clippy::arithmetic_side_effects)]
  fn before_build(builder: &mut Self::Builder, _: &mut ast::BuilderScope<C>) {
    if builder.values.chunk_size == builder.values.inner.len()
      && builder.values.inner.len() == builder.index_1.len() * builder.index_2.len()
    {
      builder.values.chunk_size = builder.index_2.len();
    }
  }
}
impl<C: Ctx> GroupFn<C> for DriverWaveform<C> {
  #[expect(clippy::arithmetic_side_effects)]
  fn before_build(builder: &mut Self::Builder, _: &mut ast::BuilderScope<C>) {
    if builder.values.chunk_size == builder.values.inner.len()
      && builder.values.inner.len() == builder.index_1.len() * builder.index_2.len()
    {
      builder.values.chunk_size = builder.index_2.len();
    }
  }
}

#[derive(Debug, Default, Clone)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct Values {
  pub chunk_size: usize,
  pub inner: Vec<f64>,
}
crate::ast::impl_self_builder!(Values);
impl<C: Ctx> ComplexAttri<C> for Values {
  #[inline]
  fn parse<'a, I: Iterator<Item = &'a &'a str>>(
    _iter: I,
    _scope: &mut ParseScope<'_>,
  ) -> Result<Self, ComplexParseError> {
    unreachable!()
  }
  #[inline]
  #[expect(clippy::arithmetic_side_effects)]
  fn nom_parse<'a>(
    i: &'a str,
    scope: &mut ParseScope<'_>,
  ) -> ast::ComplexParseRes<'a, Self> {
    match ast::parser::complex_values(i, &mut scope.loc.line_num) {
      Ok((_i, vec)) => {
        let mut chunk_size = 0;
        let mut table_len_mismatch = false;
        let inner: Vec<f64> = vec
          .into_iter()
          .flat_map(|(n, v)| {
            scope.loc.line_num += n;
            let l = v.len();
            #[expect(clippy::else_if_without_else)]
            if l != 0 {
              if chunk_size == 0 {
                chunk_size = l;
              } else if chunk_size != l {
                table_len_mismatch = true;
              }
            }
            v
          })
          .collect();
        Ok((
          _i,
          if table_len_mismatch {
            crate::error!("{} table of values is NOT aligned", scope.loc);
            Ok(Self { chunk_size: inner.len(), inner })
          } else {
            Ok(Self { chunk_size, inner })
          },
        ))
      }
      Err(_) => {
        Err(nom::Err::Error(nom::error::Error::new(i, nom::error::ErrorKind::ManyMN)))
      }
    }
  }
  #[inline]
  fn is_set(&self) -> bool {
    !self.inner.is_empty()
  }
  #[inline]
  fn fmt_self<T: Write, I: ast::Indentation>(
    &self,
    f: &mut ast::CodeFormatter<'_, T, I>,
  ) -> fmt::Result {
    let mut iter = self.inner.chunks(self.chunk_size);
    if let Some(v) = iter.next() {
      ast::join_fmt(
        v.iter(),
        f,
        |float, ff| ff.write_num(*float),
        |ff| write!(ff, ", "),
      )?;
    }
    while let Some(v) = iter.next() {
      write!(f, ", \\")?;
      f.write_new_line_indentation()?;
      ast::join_fmt(
        v.iter(),
        f,
        |float, ff| ff.write_num(*float),
        |ff| write!(ff, ", "),
      )?;
    }
    Ok(())
  }
}

#[expect(clippy::field_scoped_visibility_modifiers)]
pub(crate) struct DisplayValues<V: Iterator<Item = f64>> {
  pub(crate) len: usize,
  pub(crate) chunk_size: usize,
  pub(crate) inner: V,
}

impl<V: Iterator<Item = f64>> DisplayValues<V> {
  #[inline]
  fn fmt_self<T: Write, I: ast::Indentation>(
    self,
    f: &mut ast::CodeFormatter<'_, T, I>,
  ) -> fmt::Result {
    use itertools::Itertools as _;
    let chunks = self.inner.chunks(self.chunk_size);
    let mut iter = chunks.into_iter();
    if let Some(v) = iter.next() {
      ast::join_fmt(
        v.into_iter(),
        f,
        |float, ff| ff.write_num(float),
        |ff| write!(ff, ", "),
      )?;
    }
    while let Some(v) = iter.next() {
      write!(f, ", \\")?;
      f.write_new_line_indentation()?;
      ast::join_fmt(
        v.into_iter(),
        f,
        |float, ff| ff.write_num(float),
        |ff| write!(ff, ", "),
      )?;
    }
    Ok(())
  }
}

#[expect(clippy::field_scoped_visibility_modifiers)]
pub(crate) struct DisplayTableLookUp<'a, V: Iterator<Item = f64>> {
  pub(crate) name: &'a String,
  pub(crate) index_1: &'a Vec<f64>,
  pub(crate) index_2: &'a Vec<f64>,
  pub(crate) values: DisplayValues<V>,
}

impl<V: Iterator<Item = f64>> DisplayTableLookUp<'_, V> {
  #[inline]
  pub(crate) fn fmt_self<T: Write, I: ast::Indentation, C: Ctx>(
    self,
    key1: &str,
    key2: &str,
    f: &mut ast::CodeFormatter<'_, T, I>,
  ) -> fmt::Result {
    use core::fmt::Write as _;
    f.write_new_line_indentation()?;
    write!(f, "{key1}{key2} (")?;
    ast::NameAttri::fmt_self(self.name, f)?;
    write!(f, ") {{")?;
    f.indent();
    ComplexAttri::<C>::fmt_liberty(self.index_1, "index_1", f)?;
    ComplexAttri::<C>::fmt_liberty(self.index_2, "index_2", f)?;
    if self.values.len > 0 {
      f.write_new_line_indentation()?;
      write!(f, "values (")?;
      f.indent();
      self.values.fmt_self(f)?;
      f.dedent();
      write!(f, ");")?;
    }
    f.dedent();
    f.write_new_line_indentation()?;
    write!(f, "}}")
  }
}

#[derive(Debug, Clone)]
#[derive(liberty_macros::Group)]
#[mut_set::derive::item]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(bound = "C::Other: serde::Serialize + serde::de::DeserializeOwned")]
pub struct TableTemple<C: Ctx> {
  #[liberty(name)]
  #[id(borrow = str)]
  pub name: String,
  /// group comments
  #[liberty(comments)]
  comments: GroupComments,
  #[liberty(extra_ctx)]
  pub extra_ctx: C::Other,
  /// group undefined attributes
  #[liberty(attributes)]
  pub attributes: Attributes,
  #[liberty(simple(type = Option))]
  pub variable_1: Option<Variable>,
  #[liberty(simple(type = Option))]
  pub variable_2: Option<Variable>,
  #[liberty(simple(type = Option))]
  pub variable_3: Option<Variable>,
  #[liberty(simple(type = Option))]
  pub variable_4: Option<Variable>,
  #[liberty(complex(type = Option))]
  pub index_1: Option<Vec<f64>>,
  #[liberty(complex(type = Option))]
  pub index_2: Option<Vec<f64>>,
  #[liberty(complex(type = Option))]
  pub index_3: Option<Vec<f64>>,
  #[liberty(complex(type = Option))]
  pub index_4: Option<Vec<f64>>,
}
impl<C: Ctx> GroupFn<C> for TableTemple<C> {}

/// In Timing Delay Tables:
///
/// Following are the values that you can assign for `variable_1`, `variable_2`, and `variable_3`,
/// to the templates for timing delay tables:
/// + `input_net_transition`
/// + `total_output_net_capacitance`
/// + `output_net_length`
/// + `output_net_wire_cap`
/// + `output_net_pin_cap`
/// + `related_out_total_output_net_capacitance`
/// + `related_out_output_net_length`
/// + `related_out_output_net_wire_cap`
/// + `related_out_output_net_pin_cap`
///
/// The values that you can assign to the variables of a table specifying timing delay
/// depend on whether the table is one-, two-, or three-dimensional.
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=67.9&end=67.20
/// ">Reference-Definition</a>
///
/// In Constraint Tables:
///
/// You can assign the following values to the `variable_1`, `variable_2`, and `variable_3` variables
/// in the templates for constraint tables:
/// + `constrained_pin_transition`
/// + `related_pin_transition`
/// + `related_out_total_output_net_capacitance`
/// + `related_out_output_net_length`
/// + `related_out_output_net_wire_cap`
/// + `related_out_output_net_pin_cap`
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=67.21&end=67.28
/// ">Reference-Definition</a>
///
/// In Wire Delay Tables:
///
/// The following is the value set that you can assign for `variable_1`, `variable_2`, and `variable_3`,
/// to the templates for wire delay tables:
/// + `fanout_number`
/// + `fanout_pin_capacitance`
/// + `driver_slew`
///
/// The values that you can assign to the variables of a table specifying wire delay depends on whether the table is one-, two-, or three-dimensional.
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=67.29&end=67.34
/// ">Reference-Definition</a>
///
/// In Net Delay Tables:
///
/// The following is the value set that you can assign for `variable_1`  and `variable_2`,
/// to the templates for net delay tables:
/// + `output_transition`
/// + `rc_product`
///
/// The values that you can assign to the variables of a table specifying net delay depend on whether the table is one- or two-dimensional.
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=68.2+67.35&end=68.3+67.38
/// ">Reference-Definition</a>
///
/// In Degradation Tables:
///
/// The following values apply only to templates for transition time degradation tables:
/// + `variable_1` : `output_pin_transition` | `connect_delay` ;
/// + `variable_2` : `output_pin_transition` | `connect_delay` ;
///
/// The cell degradation table template allows only one-dimensional tables:
/// + `variable_1` : `input_net_transition`
///
/// The following rules show the relationship between the variables and indexes:
/// + If you have `variable_1`, you must have `index_1`.
/// + If you have `variable_1`  and `variable_2`, you must have `index_1`  and `index_2`.
/// + If you have `variable_1`, `variable_2`, and `variable_3`, you must have `index_1`, `index_2`, and `index_3`.
///
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=68.4&end=68.16
/// ">Reference-Definition</a>
///
/// Specify the following attributes in the vector group:
///
/// + The `index_1` attribute lists the `input_noise_height` values in library voltage units.
/// + The `index_2` attribute lists the `input_noise_width` values in library time units.
/// + The `index_3` attribute lists the `total_output_net_capacitance` values in library capacitance units.
/// + The `index_4` attribute lists the sampling `time` values in library time units.
///
/// The values attribute lists the voltage values, in library voltage units, that are measured at the channel-connecting block output node.
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=290.11&end=290.17
/// ">Reference-Definition</a>
#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum Variable {
  Time(TimeVariable),
  Voltage(VoltageVariable),
  Capacitance(CapacitanceVariable),
  RcProduct,
  Length(LengthVariable),
  Scalar(ScalarVariable),
}
crate::ast::impl_self_builder!(Variable);
crate::ast::impl_simple!(Variable);

impl Variable {
  pub const INPUT_VOLTAGE: Self = Self::Voltage(VoltageVariable::InputVoltage);
  pub const OUTPUT_VOLTAGE: Self = Self::Voltage(VoltageVariable::OutputVoltage);
  pub const INPUT_NOISE_HEIGHT: Self = Self::Voltage(VoltageVariable::InputNoiseHeight);
  pub const INPUT_TRANSITION_TIME: Self = Self::Time(TimeVariable::InputTransitionTime);
  pub const INPUT_NET_TRANSITION: Self = Self::Time(TimeVariable::InputNetTransition);
  pub const CONSTRAINED_PIN_TRANSITION: Self =
    Self::Time(TimeVariable::ConstrainedPinTransition);
  pub const RELATED_PIN_TRANSITION: Self = Self::Time(TimeVariable::RelatedPinTransition);
  pub const DRIVER_SLEW: Self = Self::Time(TimeVariable::DriverSlew);
  pub const OUTPUT_TRANSITION: Self = Self::Time(TimeVariable::OutputTransition);
  pub const OUTPUT_PIN_TRANSITION: Self = Self::Time(TimeVariable::OutputPinTransition);
  pub const CONNECT_DELAY: Self = Self::Time(TimeVariable::ConnectDelay);
  pub const INPUT_NOISE_WIDTH: Self = Self::Time(TimeVariable::InputNoiseWidth);
  pub const TIME: Self = Self::Time(TimeVariable::Time);
  pub const TOTAL_OUTPUT_NET_CAPACITANCE: Self =
    Self::Capacitance(CapacitanceVariable::TotalOutputNetCapacitance);
  pub const OUTPUT_NET_WIRE_CAP: Self =
    Self::Capacitance(CapacitanceVariable::OutputNetWireCap);
  pub const OUTPUT_NET_PIN_CAP: Self =
    Self::Capacitance(CapacitanceVariable::OutputNetPinCap);
  pub const RELATED_OUT_TOTAL_OUTPUT_NET_CAPACI: Self =
    Self::Capacitance(CapacitanceVariable::RelatedOutTotalOutputNetCapacitance);
  pub const RELATED_OUT_OUTPUT_NET_WIRE_CAP: Self =
    Self::Capacitance(CapacitanceVariable::RelatedOutOutputNetWireCap);
  pub const RELATED_OUT_OUTPUT_NET_PIN_CAP: Self =
    Self::Capacitance(CapacitanceVariable::RelatedOutOutputNetPinCap);
  pub const FANOUT_PIN_CAPACITANCE: Self =
    Self::Capacitance(CapacitanceVariable::FanoutPinCapacitance);
  pub const OUTPUT_NET_LENGTH: Self = Self::Length(LengthVariable::OutputNetLength);
  pub const RELATED_OUT_OUTPUT_NET_LENGTH: Self =
    Self::Length(LengthVariable::RelatedOutOutputNetLength);
  pub const FANOUT_NUMBER: Self = Self::Scalar(ScalarVariable::FanoutNumber);
  pub const NORMALIZED_VOLTAGE: Self = Self::Scalar(ScalarVariable::NormalizedVoltage);
  pub const RC_PRODUCT: Self = Self::RcProduct;
}

impl core::str::FromStr for Variable {
  type Err = strum::ParseError;
  #[inline]
  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(match s {
      "input_voltage" => Self::INPUT_VOLTAGE,
      "output_voltage" => Self::OUTPUT_VOLTAGE,
      "input_noise_height" => Self::INPUT_NOISE_HEIGHT,
      "input_transition_time" => Self::INPUT_TRANSITION_TIME,
      "input_net_transition" => Self::INPUT_NET_TRANSITION,
      "constrained_pin_transition" => Self::CONSTRAINED_PIN_TRANSITION,
      "related_pin_transition" => Self::RELATED_PIN_TRANSITION,
      "driver_slew" => Self::DRIVER_SLEW,
      "output_transition" => Self::OUTPUT_TRANSITION,
      "output_pin_transition" => Self::OUTPUT_PIN_TRANSITION,
      "connect_delay" => Self::CONNECT_DELAY,
      "input_noise_width" => Self::INPUT_NOISE_WIDTH,
      "time" => Self::TIME,
      "total_output_net_capacitance" => Self::TOTAL_OUTPUT_NET_CAPACITANCE,
      "output_net_wire_cap" => Self::OUTPUT_NET_WIRE_CAP,
      "output_net_pin_cap" => Self::OUTPUT_NET_PIN_CAP,
      "related_out_total_output_net_capaci" => Self::RELATED_OUT_TOTAL_OUTPUT_NET_CAPACI,
      "related_out_output_net_wire_cap" => Self::RELATED_OUT_OUTPUT_NET_WIRE_CAP,
      "related_out_output_net_pin_cap" => Self::RELATED_OUT_OUTPUT_NET_PIN_CAP,
      "fanout_pin_capacitance" => Self::FANOUT_PIN_CAPACITANCE,
      "output_net_length" => Self::OUTPUT_NET_LENGTH,
      "related_out_output_net_length" => Self::RELATED_OUT_OUTPUT_NET_LENGTH,
      "fanout_number" => Self::FANOUT_NUMBER,
      "normalized_voltage" => Self::NORMALIZED_VOLTAGE,
      "rc_product" => Self::RC_PRODUCT,
      _ => {
        return Err(strum::ParseError::VariantNotFound);
      }
    })
  }
}

impl fmt::Display for Variable {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let s = match *self {
      Self::INPUT_VOLTAGE => "input_voltage",
      Self::OUTPUT_VOLTAGE => "output_voltage",
      Self::INPUT_NOISE_HEIGHT => "input_noise_height",
      Self::INPUT_TRANSITION_TIME => "input_transition_time",
      Self::INPUT_NET_TRANSITION => "input_net_transition",
      Self::CONSTRAINED_PIN_TRANSITION => "constrained_pin_transition",
      Self::RELATED_PIN_TRANSITION => "related_pin_transition",
      Self::DRIVER_SLEW => "driver_slew",
      Self::OUTPUT_TRANSITION => "output_transition",
      Self::OUTPUT_PIN_TRANSITION => "output_pin_transition",
      Self::CONNECT_DELAY => "connect_delay",
      Self::INPUT_NOISE_WIDTH => "input_noise_width",
      Self::TIME => "time",
      Self::TOTAL_OUTPUT_NET_CAPACITANCE => "total_output_net_capacitance",
      Self::OUTPUT_NET_WIRE_CAP => "output_net_wire_cap",
      Self::OUTPUT_NET_PIN_CAP => "output_net_pin_cap",
      Self::RELATED_OUT_TOTAL_OUTPUT_NET_CAPACI => "related_out_total_output_net_capaci",
      Self::RELATED_OUT_OUTPUT_NET_WIRE_CAP => "related_out_output_net_wire_cap",
      Self::RELATED_OUT_OUTPUT_NET_PIN_CAP => "related_out_output_net_pin_cap",
      Self::FANOUT_PIN_CAPACITANCE => "fanout_pin_capacitance",
      Self::OUTPUT_NET_LENGTH => "output_net_length",
      Self::RELATED_OUT_OUTPUT_NET_LENGTH => "related_out_output_net_length",
      Self::FANOUT_NUMBER => "fanout_number",
      Self::NORMALIZED_VOLTAGE => "normalized_voltage",
      Self::RC_PRODUCT => "rc_product",
    };
    f.write_str(s)
  }
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(strum::EnumString, strum::EnumIter, strum::Display)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum TimeVariable {
  /// `input_transition_time`
  #[strum(serialize = "input_transition_time")]
  InputTransitionTime,
  /// `input_net_transition`
  #[strum(serialize = "input_net_transition")]
  InputNetTransition,
  ///`constrained_pin_transition`
  #[strum(serialize = "constrained_pin_transition")]
  ConstrainedPinTransition,
  ///`related_pin_transition`
  #[strum(serialize = "related_pin_transition")]
  RelatedPinTransition,
  /// `driver_slew`
  #[strum(serialize = "driver_slew")]
  DriverSlew,
  /// `output_transition`
  #[strum(serialize = "output_transition")]
  OutputTransition,
  /// `output_pin_transition`
  #[strum(serialize = "output_pin_transition")]
  OutputPinTransition,
  /// `connect_delay`
  #[strum(serialize = "connect_delay")]
  ConnectDelay,
  /// `input_noise_width`
  #[strum(serialize = "input_noise_width")]
  InputNoiseWidth,
  /// `time`
  #[strum(serialize = "time")]
  Time,
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(strum::EnumString, strum::EnumIter, strum::Display)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum VoltageVariable {
  /// `input_voltage`
  #[strum(serialize = "input_voltage")]
  InputVoltage,
  /// `output_voltage`
  #[strum(serialize = "output_voltage")]
  OutputVoltage,
  /// `input_noise_height`
  #[strum(serialize = "input_noise_height")]
  InputNoiseHeight,
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(strum::EnumString, strum::EnumIter, strum::Display)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum CapacitanceVariable {
  /// `total_output_net_capacitance`
  #[strum(serialize = "total_output_net_capacitance")]
  TotalOutputNetCapacitance,
  /// `output_net_wire_cap`
  #[strum(serialize = "output_net_wire_cap")]
  OutputNetWireCap,
  /// `output_net_pin_cap`
  #[strum(serialize = "output_net_pin_cap")]
  OutputNetPinCap,
  /// `related_out_total_output_net_capaci`
  #[strum(serialize = "related_out_total_output_net_capaci")]
  RelatedOutTotalOutputNetCapacitance,
  /// `related_out_output_net_wire_cap`
  #[strum(serialize = "related_out_output_net_wire_cap")]
  RelatedOutOutputNetWireCap,
  /// `related_out_output_net_pin_cap`
  #[strum(serialize = "related_out_output_net_pin_cap")]
  RelatedOutOutputNetPinCap,
  /// `fanout_pin_capacitance`
  #[strum(serialize = "fanout_pin_capacitance")]
  FanoutPinCapacitance,
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(strum::EnumString, strum::EnumIter, strum::Display)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum LengthVariable {
  /// `output_net_length`
  #[strum(serialize = "output_net_length")]
  OutputNetLength,
  /// `related_out_output_net_length`
  #[strum(serialize = "related_out_output_net_length")]
  RelatedOutOutputNetLength,
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(Ord, PartialOrd)]
#[derive(strum::EnumString, strum::EnumIter, strum::Display)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum ScalarVariable {
  /// `fanout_number`
  #[strum(serialize = "fanout_number")]
  FanoutNumber,
  /// The `normalized_voltage`  variable is specified under the
  /// `lu_table_template`  table to describe a collection of waveforms under
  /// various input slew values.
  /// For a given input slew in `index_1`  (for example, `index_1[0]` = 1.0 ns),
  /// the `index_2`  values are a set of points that represent how the voltage rises from 0 to VDD in a rise arc,
  /// or from VDD to 0 in a fall arc.
  /// <a name ="reference_link" href="
  /// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=65.38&end=65.41
  /// ">Reference-Definition</a>
  #[strum(serialize = "normalized_voltage")]
  NormalizedVoltage,
}

/// Specify the optional `sigma_type` attribute to define the type of arrival time listed in the
/// `ocv_sigma_cell_rise`, `ocv_sigma_cell_fall`, `ocv_sigma_rise_transition`, and
/// `ocv_sigma_fall_transition` group lookup tables. The values are `early`, `late`, and
/// `early_and_late`. The default is `early_and_late`.
///
/// You can specify the `sigma_type` attribute in the `ocv_sigma_cell_rise` and
/// `ocv_sigma_cell_fall` groups.
///
/// ### Syntax
/// ``` text
/// sigma_type: early | late | early_and_late;
/// ```
/// ### Example
/// ``` text
/// sigma_type: early;
/// ```
/// <a name ="reference_link" href="
/// https://zao111222333.github.io/liberty-db/2020.09/reference_manual.html?field=null&bgn=357.15&end=357.24
/// ">Reference-Definition</a>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
#[derive(Display, EnumString)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum SigmaType {
  #[strum(serialize = "early")]
  Early,
  #[strum(serialize = "late")]
  Late,
  #[default]
  #[strum(serialize = "early_and_late")]
  EarlyAndLate,
}
ast::impl_self_builder!(SigmaType);
ast::impl_simple!(SigmaType);

#[cfg(test)]
mod test {
  use crate::{
    DefaultCtx, Group as _,
    ast::{ComplexAttri, test_parse, test_parse_fmt},
  };
  #[test]
  fn values_vector32() {
    let mut scope = crate::ast::ParseScope::default();
    let (_, res) = <super::Values as ComplexAttri<DefaultCtx>>::nom_parse(
      r#"("5.4283814e-01, 5.4289214e-01, 5.4298464e-01", \
    "6.2226570e-01, 6.2225652e-01, 6.2212002e-01,");"#,
      &mut scope,
    )
    .unwrap();
    let values = res.unwrap();
    assert_eq!(values.chunk_size, 3);
  }
  #[test]
  fn values_vector31() {
    let mut scope = crate::ast::ParseScope::default();
    let (_, res) = <super::Values as ComplexAttri<DefaultCtx>>::nom_parse(
      r#"("6.2226570e-01, 6.2225652e-01, 6.2212002e-01");"#,
      &mut scope,
    )
    .unwrap();
    let values = res.unwrap();
    assert_eq!(values.chunk_size, 3);
  }
  #[test]
  fn values_vector31_badiface() {
    let mut scope = crate::ast::ParseScope::default();
    let (_, res) = <super::Values as ComplexAttri<DefaultCtx>>::nom_parse(
      r#"("6.2226570e-01 6.2225652e-01 6.2212002e-01");"#,
      &mut scope,
    )
    .unwrap();
    let values = res.unwrap();
    assert_eq!(values.chunk_size, 3);
  }
  #[test]
  fn values_scalar1() {
    let mut scope = crate::ast::ParseScope::default();
    let (_, res) = <super::Values as ComplexAttri<DefaultCtx>>::nom_parse(
      r#"("6.2226570e-01");"#,
      &mut scope,
    )
    .unwrap();
    let values = res.unwrap();
    assert_eq!(values.chunk_size, 1);
  }
  #[test]
  fn values_scalar2() {
    let mut scope = crate::ast::ParseScope::default();
    let (_, res) = <super::Values as ComplexAttri<DefaultCtx>>::nom_parse(
      r#"(6.2226570e-01);"#,
      &mut scope,
    )
    .unwrap();
    let values = res.unwrap();
    assert_eq!(values.chunk_size, 1);
  }
  #[test]
  fn table() {
    let table = test_parse_fmt::<super::TableLookUp<DefaultCtx>>(
      r#" ("CCS_RCV_TEMPLATE_0") {
      index_1("0.0186051, 0.0372112, 0.0744591");
      index_2("0.1000000, 0.2500000, 0.5000000");
      values("5.4283814e-01, 5.4289214e-01, 5.4298464e-01", \
        "6.0907950e-01, 6.0906120e-01, 6.0903281e-01,", \
        "6.2226570e-01, 6.2225652e-01, 6.2212002e-01,");
    }
    "#,
      r#"
liberty_db::table::TableLookUp (CCS_RCV_TEMPLATE_0) {
| index_1 ("0.0186051, 0.0372112, 0.0744591");
| index_2 ("0.1, 0.25, 0.5");
| values ("0.54283814, 0.54289214, 0.54298464", \
| | "0.6090795, 0.6090612, 0.60903281", \
| | "0.6222657, 0.62225652, 0.62212002");
}"#,
    );
  }
  #[test]
  fn compact_ccs_table() {
    let table = test_parse_fmt::<super::CompactCcsTable<DefaultCtx>>(
      r#" ("c_ccs_pwr_template_6") {
        values("-0.0119931,-101.1912245,", \
          "-0.0119953,-101.1912245,", \
          "-0.0119957,-101.1912245,", \
          "-0.0119957,-101.1912245,", \
          "-0.0119957,-101.1912245,", \
          "-0.0119953,-101.1912245,", \
          "-0.0119953,-101.1912245,", \
          "-0.7696603,-101.1912245,");
      }
    "#,
      r#"
liberty_db::table::CompactCcsTable (c_ccs_pwr_template_6) {
| values ("-0.0119931, -101.1912245", \
| | "-0.0119953, -101.1912245", \
| | "-0.0119957, -101.1912245", \
| | "-0.0119957, -101.1912245", \
| | "-0.0119957, -101.1912245", \
| | "-0.0119953, -101.1912245", \
| | "-0.0119953, -101.1912245", \
| | "-0.7696603, -101.1912245");
}"#,
    );
  }
  #[test]
  fn compact_ccs_power_table() {
    let table = test_parse_fmt::<super::CompactCcsPower<DefaultCtx>>(
      r#" (c_ccs_pwr_template_3) {
        values ("0.0358012, 0.0206745, 2505, 0.0480925, 1.1701594, 2506, 1.4011397, 0.0724034", \
          "-0.0481277, 0.0206745, 13, -0.0477729, 0.0, 13, -0.026014, -1.267817, 1198, 71.4506979, 0.0698575", \
          "-0.6273036, 0.0206745, 3, -0.1100034, 3.4377912, 294, 3.8867416, 0.0715863");
      }
    "#,
      r#"
liberty_db::table::CompactCcsPower (c_ccs_pwr_template_3) {
| values ("0.0358012, 0.0206745, 2505, 0.0480925, 1.1701594, 2506, 1.4011397, 0.0724034", \
| | "-0.0481277, 0.0206745, 13, -0.0477729, 0.0, 13, -0.026014, -1.267817, 1198, 71.4506979, 0.0698575", \
| | "-0.6273036, 0.0206745, 3, -0.1100034, 3.4377912, 294, 3.8867416, 0.0715863");
}"#,
    );
    println!("{table:?}");
  }
  // https://github.com/zao111222333/liberty-db/issues/28
  #[test]
  #[cfg(feature = "lut_template")]
  fn table_template() {
    use super::TableCtx as _;
    use crate::{ccsn::ReceiverCapacitanceId, pin::PinId};

    let library = test_parse::<crate::Library<DefaultCtx>>(
      r#" (ccsn) {
        lu_table_template (receiver_cap_power_template_8x8) {
          variable_1 : input_net_transition;
          index_1 ("0.0018, 0.0086, 0.0223, 0.0497, 0.1045, 0.2141, 0.4332, 0.8715");
        }
        cell (AO21D1BWP30P140) {
          pin (A1) {
            receiver_capacitance () {
              when : "A2*B";
              receiver_capacitance1_fall (receiver_cap_power_template_8x8) {
                index_1 ("0.0018, 0.0086, 0.0223, 0.0497, 0.1045, 0.2141, 0.4332, 0.8715");
                values ("0.000301151, 0.000309383, 0.000310618, 0.000311444, 0.000313263, 0.000314142, 0.000314583, 0.000314953");
              }
            }
          }
          pin (A2) {}
          pin (B) {}
        }
      }
    "#,
    );
    let cell = library.cell.get("AO21D1BWP30P140").unwrap();
    let when = cell.parse_logic_boolexpr("A2*B").unwrap();
    let receiver_capacitance = cell
      .pin
      .get(&PinId::from("A1"))
      .unwrap()
      .receiver_capacitance
      .get(&ReceiverCapacitanceId::new(None, Some(when)))
      .unwrap();
    let table_template = receiver_capacitance
      .receiver_capacitance1_fall
      .as_ref()
      .unwrap()
      .extra_ctx
      .lut_template()
      .as_ref()
      .unwrap();
    dev_utils::text_diff(
      r#"
liberty_db::table::TableTemple (receiver_cap_power_template_8x8) {
| variable_1 : input_net_transition;
| index_1 ("0.0018, 0.0086, 0.0223, 0.0497, 0.1045, 0.2141, 0.4332, 0.8715");
}"#,
      &table_template.display().to_string(),
    );
  }
}