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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
// Copyright (c) 2018-2021 Thomas Kramer.
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Defines functions to parse an OASIS data stream and populate a `Layout`.
//!
//! OASIS BNF Syntax:
//!
//! ```txt
//! <oasis-file>: <magic-bytes> START { CBLOCK | PAD | PROPERTY | <cell> | <name> }* END
//! <name>: { CELLNAME | TEXTSTRING | LAYERNAME | PROPNAME | PROPSTRING | XNAME }
//! <cell>: { CELL { CBLOCK | PAD | PROPERTY | XYRELATIVE | XYABSOLUTE | <element> }* }
//! <element>: { <geometry> | PLACEMENT | TEXT | XELEMENT }
//! <geometry>: { RECTANGLE | POLYGON | PATH | TRAPEZOID | CTRAPEZOID | CIRCLE | XGEOMETRY }
//! ```
use num_traits::Zero;
use db::layout::prelude::*;
use libreda_db as db;
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{Cursor, Read};
use fnv::{FnvHashMap as HashMap, FnvHashSet as HashSet};
use crate::base_types::RegularRepetition;
use crate::base_types::Repetition;
use crate::base_types::*;
use crate::{Modal, NameOrRef, XYMode};
#[derive(Debug, Clone)]
enum PropertyParent<CellId: Clone, ShapeId: Clone, CellInstId: Clone> {
None,
Cell(CellId),
CellName(String),
Geometry(Vec<ShapeId>),
Placement(Vec<CellInstId>),
XElement,
XGeometry,
}
/// TODO
fn read_offset_table<R: Read>(reader: &mut R) -> Result<(), OASISReadError> {
// For now this data is ignored.
let _cellname_flag = read_unsigned_integer(reader)?;
let _cellname_offset = read_unsigned_integer(reader)?;
let _textstring_flag = read_unsigned_integer(reader)?;
let _textstring_offset = read_unsigned_integer(reader)?;
let _propname_flag = read_unsigned_integer(reader)?;
let _propname_offset = read_unsigned_integer(reader)?;
let _propstring_flag = read_unsigned_integer(reader)?;
let _propstring_offset = read_unsigned_integer(reader)?;
let _layername_flag = read_unsigned_integer(reader)?;
let _layername_offset = read_unsigned_integer(reader)?;
let _xname_flag = read_unsigned_integer(reader)?;
let _xname_offset = read_unsigned_integer(reader)?;
Ok(())
}
/// TODO
fn _read_properties<R: Read>(_reader: &mut R) -> Result<(), OASISReadError> {
unimplemented!()
}
/// Read a `Repetition` if it is present, otherwise take it from the modal variables.
fn read_repetition_conditional<R: Read>(
reader: &mut R,
is_present: bool,
modal_value: &mut Option<Repetition>,
) -> Result<Repetition, OASISReadError> {
// Construct positions from a repetition if there is any.
if is_present {
let repetition = read_repetition(reader)?;
// Get previous repetition if necessary.
let repetition = match repetition {
Repetition::ReusePrevious => modal_value
.as_ref()
.cloned()
.ok_or(OASISReadError::ModalRepetitionNotDefined)?,
_ => repetition,
};
assert_ne!(
&repetition,
&Repetition::ReusePrevious,
"`modal.repetition` should never be set to `ReusePrevious`."
);
*modal_value = Some(repetition.clone()); // Remember the last repetition.
Ok(repetition)
} else {
// Return single-element repetition.
Ok(Repetition::Regular(RegularRepetition::new(
Vector::zero(),
Vector::zero(),
1,
1,
)))
}
}
/// Convert a repetition into explicit displacements.
fn repetition_to_offsets(rep: &Repetition, first_position: Vector<SInt>) -> Vec<Vector<SInt>> {
match &rep {
Repetition::ReusePrevious => {
unreachable!("`modal.repetition` should never be set to `ReusePrevious`.")
}
Repetition::Regular(r) => r.iter().map(|offset| first_position + offset).collect(),
Repetition::Irregular(r) => r.iter().map(|offset| first_position + *offset).collect(),
}
}
/// Read a x/y coordinate if it is explicitly defined, otherwise use the modal variable.
/// Relative coordinates are resolved to absolute coordinates.
/// The `modal_value` is used if the coordinate is not present.
/// The `modal_value` is updated to the current coordinate value.
fn read_coordinate_conditional<R: Read>(
reader: &mut R,
is_present: bool,
xy_mode: XYMode,
modal_value: &mut SInt,
) -> Result<SInt, OASISReadError> {
let c = if is_present {
let c = read_signed_integer(reader)?;
match xy_mode {
XYMode::Absolute => c,
XYMode::Relative => *modal_value + c,
}
} else {
*modal_value
};
*modal_value = c;
Ok(c)
}
/// Read a (layer, datatype) pair.
fn read_layernum_datatype<R: Read, C>(
reader: &mut R,
is_layer_present: bool,
is_datatype_present: bool,
modal: &mut Modal<C>,
) -> Result<(UInt, UInt), OASISReadError> {
let layer = if is_layer_present {
read_unsigned_integer(reader)?
} else {
modal.layer.ok_or(OASISReadError::NoImplicitLayerDefined)?
};
modal.layer = Some(layer);
let datatype = if is_datatype_present {
read_unsigned_integer(reader)?
} else {
modal
.datatype
.ok_or(OASISReadError::NoImplicitDataTypeDefined)?
};
modal.datatype = Some(datatype);
Ok((layer, datatype))
}
/// Tells if IDs are given implicitly by a counter or are explicitly written in the file.
#[derive(Eq, PartialEq, Debug)]
enum IdMode {
/// ID mode is not known yet.
Any,
/// IDs are given based on a counter.
Impl,
/// IDs are given explicitely.
Expl,
}
impl Default for IdMode {
fn default() -> Self {
Self::Any
}
}
/// Collection of mutable state variables used in the OASIS reader/writer.
#[derive(Debug)]
struct ReaderState<L: LayoutBase> {
modal: Modal<L::CellId>,
table_offsets_at_start: bool,
offset_table: (),
m_expect_strict_mode: bool,
m_table_cell_name: Option<UInt>,
id_counters: IdCounters,
/// Mapping from cell IDs to cell names.
m_cell_names: HashMap<UInt, String>,
/// Remember the reference numbers of cell names that have been used as a forward reference
/// where the name string was not known yet. The corresponding cell needs to be updated
/// with the name once the cell name string is found.
m_cell_names_forward_references: HashMap<UInt, L::CellId>,
/// Unresolved property name forward references.
/// Mapping from property name reference to property parents with value list.
m_property_name_forward_references: HashMap<
UInt,
Vec<(
PropertyParent<L::CellId, L::ShapeId, L::CellInstId>,
Vec<PropertyValue>,
)>,
>,
/// Mapping from property IDs to property names.
m_propnames: HashMap<UInt, String>,
/// Mapping from property string IDs to property strings.
m_propstrings: HashMap<UInt, Vec<u8>>,
/// Mapping from text string IDs to text strings.
m_textstrings: HashMap<UInt, String>,
/// The cell currently under construction.
current_cell: Option<L::CellId>,
/// Counter for generating temporary cell names if they are not yet defined.
cell_name_counter: IdCounter,
/// Remember cells that have been created as forward references in placement records.
/// They must be respected when afterwards a CELL record creates a cell with the same name.
// TODO: This is not correctly used yet.
// TODO: Put this into the mutable state struct.
placement_cell_forward_references: HashSet<L::CellId>,
/// Remember with what to associate PROPERTY records.
property_parent: PropertyParent<L::CellId, L::ShapeId, L::CellInstId>,
/// Set to `true` while reading uncompressed data of a CBLOCK.
/// Used to detect nested CBLOCKs.
is_in_cblock: bool,
}
impl<L: LayoutBase> Default for ReaderState<L> {
fn default() -> Self {
Self {
modal: Default::default(),
table_offsets_at_start: false,
offset_table: Default::default(),
m_expect_strict_mode: false,
m_table_cell_name: Default::default(),
id_counters: Default::default(),
m_cell_names: Default::default(),
m_cell_names_forward_references: Default::default(),
m_property_name_forward_references: Default::default(),
m_propnames: Default::default(),
m_propstrings: Default::default(),
m_textstrings: Default::default(),
current_cell: Default::default(),
cell_name_counter: Default::default(),
placement_cell_forward_references: Default::default(),
property_parent: PropertyParent::None,
is_in_cblock: false,
}
}
}
/// Counter for implicit IDs.
#[derive(Debug, Default)]
struct IdCounter {
id_mode: IdMode,
counter: u32,
}
impl IdCounter {
fn next(&mut self) -> u32 {
let c = self.counter;
self.counter += 1;
c
}
}
/// Counters for implicit IDs.
#[derive(Debug, Default)]
struct IdCounters {
cellname: IdCounter,
textstrings: IdCounter,
propname: IdCounter,
propstrings: IdCounter,
}
impl<L> ReaderState<L>
where
L: LayoutEdit<Coord = SInt>,
{
fn read_layout<R: Read>(
mut self,
reader: &mut R,
layout: &mut L,
) -> Result<(), OASISReadError> {
read_magic(reader)?;
self.read_start_record(reader, layout)?;
self.read_body(reader, layout)?;
Ok(())
}
fn read_start_record<R: Read>(
&mut self,
reader: &mut R,
layout: &mut L,
) -> Result<(), OASISReadError> {
let record_id = read_unsigned_integer(reader)?;
if record_id != 1 {
return Err(OASISReadError::UnexpectedRecord(record_id)); // START record expected.
}
let version_string = read_ascii_string(reader)?;
if !version_string.eq("1.0") {
return Err(OASISReadError::WrongVersionString); // Wrong version string.
}
let resolution = read_real(reader)?; // Grid steps per micron.
// If the resolution is negative, NaN or infinite return an error.
{
let r = resolution.to_f64();
if f64::is_sign_negative(r) || f64::is_infinite(r) || f64::is_nan(r) {
return Err(OASISReadError::InvalidResolution(resolution)); // Invalid resolution.
}
}
let dbu = match resolution.try_to_int() {
Some(r) if r > 0 => r as UInt,
_ => unreachable!("Resolution must be a positive non-zero integer."), // already checked above
};
assert!(dbu >= 1); // already checked above
layout.set_dbu(dbu as SInt);
// If the `offset_flag` is set to 0 then the table-offsets is stored in the START record.
// Otherwise it is stored in the END record.
let offset_flag = read_unsigned_integer(reader)?;
trace!("offset flag = {}", offset_flag);
self.table_offsets_at_start = offset_flag == 0;
if self.table_offsets_at_start {
// table-offsets is stored in START record.
self.offset_table = read_offset_table(reader)?;
}
Ok(())
}
/// Set properties of a certain object `property_parent`.
fn set_property(
layout: &mut L,
property_parent: &PropertyParent<L::CellId, L::ShapeId, L::CellInstId>,
property_name: &String,
property_values: &[PropertyValue],
// Mapping from property string references to property strings.
property_strings: &HashMap<UInt, Vec<u8>>,
) {
// Convert property values to data base types.
let property_values: Vec<db::property_storage::PropertyValue> = property_values
.iter()
.map(|v| {
use db::property_storage::PropertyValue as PV;
match v {
PropertyValue::SInt(v) => (*v).into(),
PropertyValue::UInt(v) => (*v).into(),
PropertyValue::Real(v) => match v {
Real::IEEEFloat32(v) => PV::Float(*v as f64),
Real::IEEEFloat64(v) => PV::Float(*v),
Real::PositiveWholeNumber(v) => (*v).into(),
Real::NegativeWholeNumber(v) => (0 - *v as i32).into(),
x => {
dbg!(&property_name, x);
unimplemented!();
}
},
PropertyValue::AString(s) => s.clone().into(),
PropertyValue::NString(s) => s.clone().into(),
PropertyValue::BString(s) => s.clone().into(),
PropertyValue::NStringRef(propstring_id) => {
// Fetch property string.
let bstring = property_strings
.get(propstring_id)
.expect("AString forward references are not supported yet."); // TODO
let s = bytes_to_name_string(bstring.clone())
.expect("Failed to convert bytes to name string.");
s.into()
}
PropertyValue::AStringRef(propstring_id) => {
// Fetch property string.
let bstring = property_strings
.get(propstring_id)
.expect("NString forward references are not supported yet."); // TODO
let s = bytes_to_ascii_string(bstring.clone())
.expect("Failed to convert bytes to ascii string.");
s.into()
}
PropertyValue::BStringRef(propstring_id) => {
// Fetch property string.
let bstring = property_strings
.get(propstring_id)
.expect("BString forward references are not supported yet."); // TODO
bstring.clone().into()
}
}
})
.collect();
let property_name: L::NameType = property_name.clone().into();
match &property_parent {
PropertyParent::None => {
// Properties related to the whole layout.
for v in &property_values {
layout.set_chip_property(property_name.clone(), v.clone());
}
}
PropertyParent::Geometry(shapes) => {
for shape in shapes {
for v in &property_values {
layout.set_shape_property(shape, property_name.clone(), v.clone());
}
}
}
PropertyParent::Cell(cell) => {
for v in &property_values {
layout.set_cell_property(cell, property_name.clone(), v.clone());
}
}
PropertyParent::CellName(cell_name) => {
// Properties associated with a cell name.
let cell = layout
.cell_by_name(cell_name)
.expect("Cell name not found.");
for v in &property_values {
layout.set_cell_property(&cell, property_name.clone(), v.clone());
}
}
PropertyParent::Placement(instances) => {
for instance in instances {
for v in &property_values {
layout.set_cell_instance_property(
instance,
property_name.clone(),
v.clone(),
);
}
}
}
PropertyParent::XElement => {
warn!("Storing properties for XElement is not supported yet.");
}
PropertyParent::XGeometry => {
warn!("Storing properties for XGeometry is not supported yet.");
}
}
}
/// Generate a new cell name for cases when the name is not yet specified.
fn new_cell_name(&mut self) -> L::NameType {
format!("$${}$$", self.cell_name_counter.next()).into()
}
fn read_body<R: Read>(&mut self, reader: &mut R, layout: &mut L) -> Result<(), OASISReadError> {
loop {
let record_id = match read_unsigned_integer(reader) {
Ok(id) => id,
Err(e) => match e {
OASISReadError::UnexpectedEndOfFile if self.is_in_cblock => {
// TODO: This is not quite correct.
// If a partial record ID can be read, then the error should be passed to the caller.
break;
}
other => return Err(other),
},
};
trace!("record_id = {}", record_id);
match record_id {
0 => {
// PAD record
}
1 => {
// START record
trace!("START record");
return Err(OASISReadError::UnexpectedRecord(record_id)); // No start record expected.
}
2 => {
self.read_end_record(reader)?;
break;
}
3 | 4 => self.read_cell_name(reader, layout, record_id)?,
5 | 6 => {
// TEXTSTRING record, associates a text string with a unique reference number.
trace!("TEXTSTRING record");
let textstring = read_ascii_string(reader)?;
let id = if record_id == 5 {
// Implicit IDs.
if self.id_counters.textstrings.id_mode == IdMode::Expl {
return Err(OASISReadError::MixedImplExplTextstringModes);
// Implicit and explicit TEXTSTRING modes cannot be mixed.
};
self.id_counters.textstrings.id_mode = IdMode::Impl; // Remember mode.
self.id_counters.textstrings.next()
} else {
// Explicit IDs.
if self.id_counters.textstrings.id_mode == IdMode::Impl {
return Err(OASISReadError::MixedImplExplTextstringModes);
// Implicit and explicit TEXTSTRING modes cannot be mixed.
};
self.id_counters.textstrings.id_mode = IdMode::Expl; // Remember mode.
read_unsigned_integer(reader)?
};
// Store text string.
if self.m_textstrings.insert(id, textstring).is_some() {
return Err(OASISReadError::TextStringAlreadyPresent(id));
}
self.modal.reset();
}
7 | 8 => {
// PROPNAME record, associates property name with a unique reference number.
trace!("PROPNAME record");
let property_name = read_name_string(reader)?;
trace!("property_name = {}", &property_name);
let prop_name_id = if record_id == 7 {
// Implicit IDs.
if self.id_counters.propname.id_mode == IdMode::Expl {
return Err(OASISReadError::MixedImplExplPropnameModes);
// Implicit and explicit CELLNAME modes cannot be mixed.
};
self.id_counters.propname.id_mode = IdMode::Impl; // Remember mode.
self.id_counters.propname.next() // Infinite sequence, unwrap does not fail.
} else {
// Explicit IDs.
if self.id_counters.propname.id_mode == IdMode::Impl {
return Err(OASISReadError::MixedImplExplPropnameModes);
// Implicit and explicit CELLNAME modes cannot be mixed.
};
self.id_counters.propname.id_mode = IdMode::Expl; // Remember mode.
read_unsigned_integer(reader)?
};
trace!("prop_id = {}", prop_name_id);
// TODO: Property forward references without property-string forward references could be resolved already.
// Store property name by the reference number.
if let Some(_existing_name) =
self.m_propnames.insert(prop_name_id, property_name)
{
return Err(OASISReadError::PropnameIdAlreadyPresent(prop_name_id));
}
self.modal.reset();
}
9 | 10 => {
// PROPSTRING record, associates a property string with a unique reference number.
// The property string can be an a-string, b-string or n-string depending on the
// referencing property record (28).
trace!("PROPSTRING record");
// `propstring` is a a-string, n-string or b-string depending on the referencing
// PROPERTY record.
let propstring = read_byte_string(reader)?;
trace!("propstring = {:?}", &propstring);
let id = if record_id == 9 {
// Implicit IDs.
if self.id_counters.propstrings.id_mode == IdMode::Expl {
return Err(OASISReadError::MixedImplExplPropstringModes);
// Implicit and explicit PROPSTRING modes cannot be mixed.
};
self.id_counters.propstrings.id_mode = IdMode::Impl; // Remember mode.
self.id_counters.propstrings.next() // Infinite sequence, unwrap does not fail.
} else {
// Explicit IDs.
if self.id_counters.propstrings.id_mode == IdMode::Impl {
return Err(OASISReadError::MixedImplExplPropstringModes);
// Implicit and explicit PROPSTRING modes cannot be mixed.
};
self.id_counters.propstrings.id_mode = IdMode::Expl; // Remember mode.
read_unsigned_integer(reader)?
};
// Store text string.
if let Some(_existing_name) = self.m_propstrings.insert(id, propstring) {
// Conflict: Property string ID is already used.
return Err(OASISReadError::PropStringAlreadyPresent(id));
}
self.modal.reset();
}
11 | 12 => {
// LAYERNAME record
trace!("LAYERNAME record");
let layer_name = read_name_string(reader)?;
trace!("layer_name = {}", &layer_name);
let read_interval = |reader: &mut R| {
let interval_type = read_unsigned_integer(reader)?;
let max = UInt::MAX; // Maximum integer value. Used as a pseudo representation for infinity.
match interval_type {
0 => Ok((0, max)),
1 => Ok((0, read_unsigned_integer(reader)?)),
2 => Ok((read_unsigned_integer(reader)?, max)),
3 => {
let a = read_unsigned_integer(reader)?;
Ok((a, a))
}
4 => Ok((
read_unsigned_integer(reader)?,
read_unsigned_integer(reader)?,
)),
t => Err(OASISReadError::IllegalIntervalType(t)), // Invalid interval type.
}
};
let (layer_start, layer_end) = read_interval(reader)?;
let (dtype_start, dtype_end) = read_interval(reader)?;
// Set the layer name in the layout.
let layer_name: L::NameType = layer_name.clone().into();
for l in layer_start..layer_end {
for d in dtype_start..dtype_end {
let idx = layout.find_or_create_layer(l, d);
layout.set_layer_name(&idx, Some(layer_name.clone()));
}
}
// Reset modal variables.
self.modal.reset();
warn!("LAYERNAME record is not implemented: '{}'", &layer_name);
}
13 | 14 => {
// 13: CELL record, with reference-number for the name.
// 14: CELL record, with name string.
trace!("CELL record");
// All subsequent records in the file up to the next CELL, END, or <name> record
// are considered to be part of that cell.
let cell_name = if record_id == 13 {
// Name by reference.
let cell_name_reference = read_unsigned_integer(reader)?;
let cell_name = self.m_cell_names.get(&cell_name_reference);
// Return the name if it is present, other wise return the reference number.
if let Some(cell_name) = cell_name {
NameOrRef::Name(cell_name.clone())
} else {
NameOrRef::NameRef(cell_name_reference)
}
} else {
NameOrRef::Name(read_name_string(reader)?)
};
trace!("cell_name = {:?}", &cell_name);
// Set the cell name if it is already defined.
// Otherwise remember the forward reference such that the name can be defined later.
let cell_idx = match cell_name {
NameOrRef::Name(n) => {
if let Some(cell_idx) = layout.cell_by_name(&n) {
// Cell with this name already exists.
// This is fine if it has been created as a forward reference for a placement record.
// Check if it is a forward reference to a placement record.
if self.placement_cell_forward_references.remove(&cell_idx) {
// Cell has been created as a forward reference. No name clash.
cell_idx
} else {
// Cell has not been created as a forward reference. Name clash.
return Err(OASISReadError::CellnameAlreadyPresent(n));
}
} else {
layout.create_cell(n.into())
}
}
NameOrRef::NameRef(r) => {
// Check if the reference does not already exist.
if let Some(cell_idx) = self.m_cell_names_forward_references.get(&r) {
if self.placement_cell_forward_references.remove(cell_idx) {
// Cell has been created as a forward reference. No name reference clash.
cell_idx.clone()
} else {
// Cell has not been created as a forward reference. Name reference clash.
return Err(OASISReadError::CellnameIdAlreadyPresent(r));
}
} else {
// The value of this reference has not yet been defined. Generate a temporary name.
let cell_idx = layout.create_cell(self.new_cell_name());
// Remember the forward reference.
self.m_cell_names_forward_references
.insert(r, cell_idx.clone());
cell_idx
}
}
};
// Remember this cell as the 'active' cell.
self.current_cell = Some(cell_idx.clone());
// Associate following properties with this cell for now.
self.property_parent = PropertyParent::Cell(cell_idx);
// Reset modal values.
self.modal.reset();
}
15 => {
// XYABSOLUTE record
trace!("XYABSOLUTE record");
self.modal.xy_mode = XYMode::Absolute;
}
16 => {
// XYRELATIVE record
trace!("XYRELATIVE record");
self.modal.xy_mode = XYMode::Relative;
}
17 | 18 => {
// PLACEMENT record
// 17/18 are different in how the magnification and rotation are encoded.
trace!("PLACEMENT record");
let placement_info_byte = read_byte(reader)?;
let b = |index| (placement_info_byte >> index) & 1u8 == 1u8;
let is_cell_reference_explicit = b(7); // C
let is_cell_reference_number_present = b(6); // N
let is_x_present = b(5); // X
let is_y_present = b(4); // Y
let is_repetition_present = b(3); // R
let is_flip = b(0); // F
// Get either a reference to the cell to be instantiated or at least the name to it.
// It is possible that this is a forward reference with the cell not yet defined.
let instance_ref = if is_cell_reference_explicit {
// Read cell name.
let cell_name = if is_cell_reference_number_present {
// Cell name is given by reference number.
let cell_name_ref = read_unsigned_integer(reader)?;
// Get cell name if it is already defined.
if let Some(cell_name) = self.m_cell_names.get(&cell_name_ref) {
NameOrRef::Name(cell_name.clone())
} else {
NameOrRef::NameRef(cell_name_ref)
}
} else {
// Read explicit cell name.
NameOrRef::Name(read_name_string(reader)?)
};
// Get the cell by the name or create it if necessary.
// If the cell needs to be created but no name is defined yet
// an unnamed cell will be created.
// TODO: FIXME: What if a cell is placed once by name and once by reference before it is created and before the name is defined?
// "Use of a reference-number for which there is no corresponding CELLNAME
// record should be treated as a fatal error"
match cell_name {
NameOrRef::Name(n) => {
if let Some(cell) = layout.cell_by_name(&n) {
cell
} else {
let cell = layout.create_cell(n.into());
// Remember that this cell has been created as a forward reference.
self.placement_cell_forward_references.insert(cell.clone());
cell
}
}
NameOrRef::NameRef(r) => {
// Try to find the cell by forward reference (if the name is not yet defined).
self.m_cell_names_forward_references
.get(&r)
.cloned()
// If no forward reference can be found, create a new cell
// and a new forward reference.
.unwrap_or_else(|| {
// Create an unnamed cell.
let cell = layout.create_cell(self.new_cell_name());
self.m_cell_names_forward_references
.insert(r, cell.clone());
// Remember that this cell has been created as a forward reference.
self.placement_cell_forward_references.insert(cell.clone());
cell
})
}
}
} else {
// Implicit cell.
// Use modal variable `placement_cell` which refers to the same cell as the placement record before.
self.modal
.placement_cell
.clone()
.ok_or(OASISReadError::ModalPlacementCellNotDefined)?
};
// Remember the last placement cell if any.
self.modal.placement_cell = Some(instance_ref.clone());
// Read magnification and angle or take default values.
let (magnification, angle_degrees) = if record_id == 17 {
let aa = (placement_info_byte >> 1) & 3u8; // AA
let angle_degrees = 90 * (aa as u16);
let magnification = 1;
(
Real::PositiveWholeNumber(magnification),
Real::PositiveWholeNumber(angle_degrees.into()),
)
} else {
// Magnification and rotation are reals.
let is_magnification_present = b(2); // M
let is_angle_present = b(1); // A
// Read magnification and angle (default are 1.0 and 0.0).
let magnification = if is_magnification_present {
read_real(reader)?
} else {
Real::PositiveWholeNumber(1)
};
// Read rotation angle default is 0.
let angle_degrees = if is_angle_present {
read_real(reader)?
} else {
Real::PositiveWholeNumber(0)
};
(magnification, angle_degrees)
};
// Read x.
let x = read_coordinate_conditional(
reader,
is_x_present,
self.modal.xy_mode,
&mut self.modal.placement_x,
)?;
// Read y.
let y = read_coordinate_conditional(
reader,
is_y_present,
self.modal.xy_mode,
&mut self.modal.placement_y,
)?;
// Construct placement offset.
let displacement = Vector::new(x, y);
// Construct positions from a repetition if there is any.
let repetition = read_repetition_conditional(
reader,
is_repetition_present,
&mut self.modal.repetition,
)?;
// Convert angle back into a multiple of 90 degrees if possible.
let angle90 = match angle_degrees.try_to_int() {
Some(0) => Some(Angle::R0),
Some(90) => Some(Angle::R90),
Some(180) => Some(Angle::R180),
Some(270) => Some(Angle::R270),
_ => None,
}
.expect("Rotation angle must be a multiple of 90 degree."); // TODO: Support complex transforms here.
// TODO: Support non-integer magnification.
let magnification = magnification
.try_to_int()
.expect("Magnification mut be an integer.");
// Convert the repetition into actual offsets.
let positions = repetition_to_offsets(&repetition, displacement);
// Create cell instances.
// TODO: Create cell instance arrays.
let parent_cell = self
.current_cell
.as_ref()
.ok_or(OASISReadError::NoCellRecordPresent)?;
let mut instances = Vec::with_capacity(positions.len());
for pos in positions {
let trans = SimpleTransform::new(is_flip, angle90, magnification, pos);
let inst = layout.create_cell_instance(parent_cell, &instance_ref, None);
layout.set_transform(&inst, trans);
instances.push(inst);
}
// Associate following properties with this instance for now.
self.property_parent = PropertyParent::Placement(instances);
}
19 => {
// TEXT record
trace!("TEXT record");
let text_info_byte = read_byte(reader)?;
let b = |index| (text_info_byte >> index) & 1u8 == 1u8;
let is_text_reference_explicit = b(6); // C
let text_string = if is_text_reference_explicit {
let reference_number_present = b(5);
if reference_number_present {
let ref_number = read_unsigned_integer(reader)?;
let text_string = self.m_textstrings.get(&ref_number);
text_string
.cloned()
.ok_or(OASISReadError::PropStringIdNotFound(ref_number))?
} else {
read_ascii_string(reader)?
}
} else {
self.modal
.text_string
.as_ref()
.cloned()
.ok_or(OASISReadError::NoImplicitTextStringDefined)?
};
trace!("text_string = {}", &text_string);
self.modal.text_string = Some(text_string.clone());
let is_explicit_textlayer = b(0);
let is_explicit_texttype = b(1);
let is_repetition_present = b(2);
let is_x_present = b(4);
let is_y_present = b(3);
let textlayer = if is_explicit_textlayer {
read_unsigned_integer(reader)?
} else {
self.modal
.textlayer
.ok_or(OASISReadError::ModalTextLayerDefined)?
};
self.modal.textlayer = Some(textlayer);
let texttype = if is_explicit_texttype {
read_unsigned_integer(reader)?
} else {
self.modal
.texttype
.ok_or(OASISReadError::ModalTextTypeDefined)?
};
self.modal.texttype = Some(texttype);
// Read x.
let x = read_coordinate_conditional(
reader,
is_x_present,
self.modal.xy_mode,
&mut self.modal.text_x,
)?;
// Read y.
let y = read_coordinate_conditional(
reader,
is_y_present,
self.modal.xy_mode,
&mut self.modal.text_y,
)?;
// Construct the coordinate of the first text instance (there might be a repetition).
let pos = Vector::new(x, y);
// Construct positions from a repetition if there is any.
let repetition = read_repetition_conditional(
reader,
is_repetition_present,
&mut self.modal.repetition,
)?;
let positions = repetition_to_offsets(&repetition, pos);
let parent_cell = self
.current_cell
.as_ref()
.ok_or(OASISReadError::NoCellRecordPresent)?;
let layer_id = layout.find_or_create_layer(textlayer, texttype);
let mut shape_instances = Vec::with_capacity(positions.len());
// Create text instances.
// TODO: Use L::NameType for strings. They might be cheaper to clone than `String`.
itertools::repeat_n(text_string, positions.len()) // Avoid cloning for the last instance.
.zip(positions)
.for_each(|(text_string, pos)| {
let text = Text::new(text_string, pos.into());
let shape_id = layout.insert_shape(parent_cell, &layer_id, text.into());
shape_instances.push(shape_id); // Remember all instances.
});
// Remember the shapes to associate upcoming properties with them.
self.property_parent = PropertyParent::Geometry(shape_instances);
}
20 => {
// RECTANGLE record.
trace!("RECTANGLE record");
let rectangle_info_byte = read_byte(reader)?;
let b = |index| (rectangle_info_byte >> index) & 1u8 == 1u8;
let is_layer_number_present = b(0);
let is_datatype_number_present = b(1);
let is_width_present = b(6); // W
let is_height_present = b(5); // H
let is_x_present = b(4); // X
let is_y_present = b(3); // Y
let is_repetition_present = b(2); // R
let is_square = b(7); // S
let (layer, datatype) = read_layernum_datatype(
reader,
is_layer_number_present,
is_datatype_number_present,
&mut self.modal,
)?;
let width = if is_width_present {
read_unsigned_integer(reader)?
} else {
self.modal
.geometry_w
.ok_or(OASISReadError::ModalGeometryWNotDefined)?
};
self.modal.geometry_w = Some(width);
let height = if is_square {
if is_height_present {
// `height` should not be present if S is 1.
return Err(OASISReadError::HeightIsPresentForSquare);
} else {
width
}
} else if is_height_present {
read_unsigned_integer(reader)?
} else {
self.modal
.geometry_h
.ok_or(OASISReadError::ModalGeometryHNotDefined)?
};
self.modal.geometry_h = Some(height);
// Read x.
let x = read_coordinate_conditional(
reader,
is_x_present,
self.modal.xy_mode,
&mut self.modal.geometry_x,
)?;
// Read y.
let y = read_coordinate_conditional(
reader,
is_y_present,
self.modal.xy_mode,
&mut self.modal.geometry_y,
)?;
// Construct the coordinate of the first text instance (there might be a repetition).
let pos = Vector::new(x, y);
// Construct positions from a repetition if there is any.
let repetition = read_repetition_conditional(
reader,
is_repetition_present,
&mut self.modal.repetition,
)?;
let positions = repetition_to_offsets(&repetition, pos);
let diagonal = Vector::new(width as SInt, height as SInt);
let lower_left = Point::zero();
let rect = Rect::new(lower_left, lower_left + diagonal);
if let Some(parent_cell) = &self.current_cell {
let layer_id = layout.find_or_create_layer(layer, datatype);
let mut shape_instances = Vec::new();
// Create rectangle instances.
for pos in positions {
let r = Rect::new(rect.lower_left() + pos, rect.upper_right() + pos);
let shape_id = layout.insert_shape(parent_cell, &layer_id, r.into());
shape_instances.push(shape_id); // Remember all instances.
}
// Remember the shapes to associate upcoming properties with them.
self.property_parent = PropertyParent::Geometry(shape_instances);
} else {
return Err(OASISReadError::NoCellRecordPresent);
}
}
21 => {
// POLYGON record.
trace!("POLYGON record");
let polygon_info_byte = read_byte(reader)?;
let b = |index| (polygon_info_byte >> index) & 1u8 == 1u8;
let is_layer_number_present = b(0); // L
let is_datatype_number_present = b(1); // D
let is_repetition_present = b(2); // R
let is_y_present = b(3); // Y
let is_x_present = b(4); // X
let is_pointlist_present = b(5); // P
let (layer, datatype) = read_layernum_datatype(
reader,
is_layer_number_present,
is_datatype_number_present,
&mut self.modal,
)?;
if is_pointlist_present {
let p = read_point_list(reader)?;
self.modal.polygon_point_list = Some(p);
}
// Read x.
let x = read_coordinate_conditional(
reader,
is_x_present,
self.modal.xy_mode,
&mut self.modal.geometry_x,
)?;
// Read y.
let y = read_coordinate_conditional(
reader,
is_y_present,
self.modal.xy_mode,
&mut self.modal.geometry_y,
)?;
let point0 = Vector::new(x, y);
// Create coordinates.
let points: Vec<_> = self
.modal
.polygon_point_list
.as_ref()
.ok_or(OASISReadError::ModalPolygonPointListNotDefined)
.map(|pointlist| pointlist.points(Vector::zero(), true))?;
// Construct positions from a repetition if there is any.
let repetition = read_repetition_conditional(
reader,
is_repetition_present,
&mut self.modal.repetition,
)?;
let positions = repetition_to_offsets(&repetition, point0);
let polygon = SimplePolygon::new(points).normalized_orientation::<i64>();
if let Some(parent_cell) = &self.current_cell {
let layer_id = layout.find_or_create_layer(layer, datatype);
// Repeat polygon and add the repetitions to the current cell.
let mut shape_instances = Vec::with_capacity(positions.len());
// Create polygon instances.
itertools::repeat_n(polygon, positions.len()) // Avoid cloning for the last instance.
.zip(positions)
.for_each(|(mut polygon, pos)| {
// Translate the polygon to the position.
// This is a hack around the implementation of `polygon.translate()` which unnecessarily normalizes the polygon orientation.
polygon.with_points_mut(|points| {
points.iter_mut().for_each(|point| *point += pos)
});
let shape_id =
layout.insert_shape(parent_cell, &layer_id, polygon.into());
shape_instances.push(shape_id); // Remember all instances.
});
// Remember the shapes to associate upcoming properties with them.
self.property_parent = PropertyParent::Geometry(shape_instances);
} else {
return Err(OASISReadError::NoCellRecordPresent);
}
}
22 => {
// PATH record.
trace!("PATH record");
let path_info_byte = read_byte(reader)?;
let b = |index| (path_info_byte >> index) & 1u8 == 1u8;
let is_layer_number_present = b(0); // L
let is_datatype_number_present = b(1); // D
let is_repetition_present = b(2); // R
let is_y_present = b(3); // Y
let is_x_present = b(4); // X
let is_pointlist_present = b(5); // P
let is_half_width_present = b(6); // W
let is_extension_scheme_present = b(7); // E
let (layer, datatype) = read_layernum_datatype(
reader,
is_layer_number_present,
is_datatype_number_present,
&mut self.modal,
)?;
let half_width = if is_half_width_present {
let hw = read_unsigned_integer(reader)?;
self.modal.path_halfwidth = Some(hw);
hw
} else {
self.modal
.path_halfwidth
.ok_or(OASISReadError::ModalPathHalfWidthNotDefined)?
};
let (start_ext, end_ext) = if is_extension_scheme_present {
let ext_scheme = read_unsigned_integer(reader)?;
let ss = (ext_scheme >> 2) & 0b11; // Path start extension.
let ee = ext_scheme & 0b11; // Path end extension.
let start_ext = match ss {
0 => self
.modal
.path_start_extension
.ok_or(OASISReadError::ModalPathStartExtensionNotDefined)?,
1 => 0, // 'Flush'
2 => half_width as SInt,
3 => read_signed_integer(reader)?,
_ => unreachable!(), // This cannot happen.
};
let end_ext = match ee {
0 => self
.modal
.path_end_extension
.ok_or(OASISReadError::ModalPathEndExtensionNotDefined)?,
1 => 0, // 'Flush'
2 => half_width as SInt,
3 => read_signed_integer(reader)?,
_ => unreachable!(), // This cannot happen.
};
(start_ext, end_ext)
} else {
let s = self
.modal
.path_start_extension
.ok_or(OASISReadError::ModalPathStartExtensionNotDefined)?;
let e = self
.modal
.path_end_extension
.ok_or(OASISReadError::ModalPathEndExtensionNotDefined)?;
(s, e)
};
self.modal.path_start_extension = Some(start_ext);
self.modal.path_end_extension = Some(end_ext);
if is_pointlist_present {
let p = read_point_list(reader)?;
self.modal.path_point_list = Some(p);
}
// Read x and set modal geometry_x.
let x = read_coordinate_conditional(
reader,
is_x_present,
self.modal.xy_mode,
&mut self.modal.geometry_x,
)?;
// Read y and set modal geometry_y.
let y = read_coordinate_conditional(
reader,
is_y_present,
self.modal.xy_mode,
&mut self.modal.geometry_y,
)?;
let point0 = Vector::new(x, y);
// Construct positions from a repetition if there is any.
let repetition = read_repetition_conditional(
reader,
is_repetition_present,
&mut self.modal.repetition,
)?;
let positions = repetition_to_offsets(&repetition, point0);
// Create coordinates.
let points: Vec<_> = self
.modal
.path_point_list
.as_ref()
.ok_or(OASISReadError::ModalPathPointListNotDefined)
.map(|pointlist| pointlist.points(Vector::zero(), false))?;
// Create untranslated path.
let path =
Path::new_extended(points, half_width as SInt * 2, start_ext, end_ext);
if let Some(parent_cell) = &self.current_cell {
let layer_id = layout.find_or_create_layer(layer, datatype);
// Repeat shape and add the repetitions to the current cell.
let mut shape_instances = Vec::with_capacity(positions.len());
// Create path instances.
itertools::repeat_n(path, positions.len()) // Avoid cloning for the last instance.
.zip(positions)
.for_each(|(mut path, pos)| {
// Translate the path in-place.
path.points.points.iter_mut().for_each(|p| *p += pos);
let shape_id =
layout.insert_shape(parent_cell, &layer_id, path.into());
shape_instances.push(shape_id); // Remember all instances.
});
// Remember the shapes to associate upcoming properties with them.
self.property_parent = PropertyParent::Geometry(shape_instances);
} else {
return Err(OASISReadError::NoCellRecordPresent);
}
}
28 | 29 => self.read_property_record(reader, layout, record_id)?,
30 | 31 => {
// XNAME record
trace!("XNAME record");
let _xname_attribute = read_unsigned_integer(reader)?;
let _xname_string = read_byte_string(reader)?;
if record_id == 31 {
let _reference_number = read_unsigned_integer(reader)?;
}
self.modal.reset();
// TODO: This is neither complete nor correct.
unimplemented!("XNAME record is not supported yet.")
}
32 => {
// XELEMENT record
trace!("XELEMENT record");
let _xelement_attribute = read_unsigned_integer(reader)?;
let _xelement_string = read_byte_string(reader)?; // Contains user defined data.
self.property_parent = PropertyParent::XElement;
}
33 => {
// XGEOMETRY record
trace!("XGEOMETRY record");
// TODO: This is neither complete nor correct.
self.property_parent = PropertyParent::XGeometry;
unimplemented!("XGEOMETRY record is not supported yet.")
}
34 => {
// CBLOCK
trace!("CBLOCK");
if self.is_in_cblock {
log::error!("nested CBLOCK");
return Err(OASISReadError::NestedCblock);
}
let compression_type = read_unsigned_integer(reader)?;
if compression_type != 0 {
return Err(OASISReadError::UnsupportedCompressionType(compression_type));
}
let uncompressed_byte_count = read_unsigned_integer(reader)? as usize;
let compressed_byte_count = read_unsigned_integer(reader)?;
trace!("read compressed bytes: {} bytes", compressed_byte_count);
let mut compressed_bytes = vec![0; compressed_byte_count as usize];
reader.read_exact(&mut compressed_bytes)?;
// TODO: Instead of copying data decompress directly on the stream as KLayout does.
// For example use flate2::read::DeflateDecoder.
trace!("deflate CBLOCK");
let mut decompressor = flate2::Decompress::new(false);
let mut uncompressed_bytes =
Vec::with_capacity(uncompressed_byte_count.min(1 << 20));
decompressor
.decompress_vec(
&compressed_bytes,
&mut uncompressed_bytes,
flate2::FlushDecompress::Finish,
)
.map_err(|_e| OASISReadError::DecompressError)?;
// Announced and actual size of the uncompressed data must match.
if uncompressed_bytes.len() != uncompressed_byte_count {
return Err(OASISReadError::UncompressedByteCountMismatch(
uncompressed_byte_count,
uncompressed_bytes.len(),
));
}
self.is_in_cblock = true;
let result = self.read_body(&mut Cursor::new(uncompressed_bytes), layout);
self.is_in_cblock = false;
result?;
}
_ => {
return Err(OASISReadError::UnsupportedRecordType(record_id));
}
}
}
// Resolve property forward references.
// if let Some(forward_references) = self.m_property_name_forward_references.remove(&prop_name_id) {
for (prop_name_id, forward_references) in self.m_property_name_forward_references.drain() {
let property_name = self.m_propnames.get(&prop_name_id).unwrap();
trace!(
"Resolve {} forward references '{}=>{}'.",
forward_references.len(),
prop_name_id,
&property_name
);
for (property_parent, property_values) in forward_references {
Self::set_property(
layout,
&property_parent,
property_name,
&property_values,
&self.m_propstrings,
);
}
}
// Check for cells that never had their name defined.
if !self.m_cell_names_forward_references.is_empty() {
error!("Some cell name forward references where not resolved.");
return Err(OASISReadError::UnresolvedForwardReferences(
self.m_cell_names_forward_references
.keys()
.copied()
.collect(),
));
}
debug_assert!(
self.placement_cell_forward_references.is_empty(),
"Some forward references have never been resolved."
);
// Check that all property forward reference have been resolved.
if !self.m_property_name_forward_references.is_empty() {
error!("Some property name forward references where not resolved.");
return Err(OASISReadError::UnresolvedForwardReferences(
self.m_property_name_forward_references
.keys()
.copied()
.collect(),
));
}
Ok(())
}
fn read_end_record<R: Read>(&mut self, reader: &mut R) -> Result<(), OASISReadError> {
// END record.
trace!("END record");
// Finished reading file.
if !self.table_offsets_at_start {
// table-offsets is stored in END record.
read_offset_table(reader)?;
}
// The padding string makes sure that the byte length of the END record inclusive record-ID is exactly 256.
let _padding_string = read_byte_string(reader)?;
// Type of integrity check: None, CRC32 or CHECKSUM32.
let validation_scheme = read_unsigned_integer(reader)?;
match validation_scheme {
0 => {
// No validation.
trace!("No integrity validation.");
}
1 => {
// CRC32, checksum length = 4
let crc32_expected = reader.read_u32::<LittleEndian>()?;
trace!("CRC32 (from file): {:x}", crc32_expected);
// TODO: Validate checksum
}
2 => {
// CHECKSUM32, checksum length = 4
// CHECKSUM32 is the simple arithmetic addition of all bytes from the first
// byte of the START record until the `validation_scheme` byte of this END record.
let checksum32_expected = reader.read_u32::<LittleEndian>()?;
trace!("CHECKSUM32 (from file): {:x}", checksum32_expected);
// TODO: Validate checksum
}
v => {
return Err(OASISReadError::UnknownValidationScheme(v)); // Invalid validation scheme.
}
}
Ok(())
}
// fn read_xyz<R: Read>(&mut self, reader: &mut R, layout: &mut L) -> Result<(), OASISReadError> {
// Ok(())
// }
fn read_cell_name<R: Read>(
&mut self,
reader: &mut R,
layout: &mut L,
record_id: u32,
) -> Result<(), OASISReadError> {
// CELLNAME record
trace!("CELLNAME record");
let cell_name = read_name_string(reader)?;
trace!("cell name = {}", &cell_name);
let id = if record_id == 3 {
// Implicit IDs.
if self.id_counters.cellname.id_mode == IdMode::Expl {
return Err(OASISReadError::MixedImplExplCellnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
};
self.id_counters.cellname.id_mode = IdMode::Impl; // Remember mode.
self.id_counters.cellname.next() // Infinite sequence, unwrap does not fail.
} else {
// Explicit IDs.
if self.id_counters.cellname.id_mode == IdMode::Impl {
return Err(OASISReadError::MixedImplExplCellnameModes); // Implicit and explicit CELLNAME modes cannot be mixed.
};
self.id_counters.cellname.id_mode = IdMode::Expl; // Remember mode.
read_unsigned_integer(reader)?
};
// Store cell name.
// Return an error if the cell name already exists.
if self.m_cell_names.insert(id, cell_name.clone()).is_some() {
return Err(OASISReadError::CellnameIdAlreadyPresent(id));
}
self.modal.reset();
// Resolve forward references.
if let Some(idx) = self.m_cell_names_forward_references.remove(&id) {
// TODO: Handle case when name is already used.
if let Some(_existing_cell) = layout.cell_by_name(&cell_name) {
warn!("Cell already exists: {}", cell_name);
// Find a cell name that does not exit by appending a counter.
// let new_cell_name = (1..).into_iter()
// .map(|i| format!("{}$${}", cell_name, i))
// .find(|name| layout.cell_by_name(name).is_none())
// .unwrap();
}
layout.rename_cell(&idx, cell_name.clone().into());
}
// Subsequent PROPERTY records may be associated with the cell with this name.
self.property_parent = PropertyParent::CellName(cell_name);
Ok(())
}
fn read_property_record<R: Read>(
&mut self,
reader: &mut R,
layout: &mut L,
record_id: u32,
) -> Result<(), OASISReadError> {
// PROPERTY record.
// PROPERTY records follow the records they are associated with.
// Updates `last_property_name` and `last_value_list` modal variables.
// 29 specifies a duplicate of the most recently seen property.
trace!("PROPERTY record");
let (property_name_or_ref, property_values) = if record_id == 28 {
let prop_info_byte = read_byte(reader)?;
let b = |index| (prop_info_byte >> index) & 1u8 == 1u8;
let is_name_reference_explicit = b(2); // C
let use_last_value_list = b(3); // V
let _is_standard_property = b(0); // S, TODO: How to handle this?
let uuuu = ((prop_info_byte >> 4) & 0xF).into(); // Upper nibble.
let property_name_or_ref = if is_name_reference_explicit {
let is_ref_number_present = b(1);
if is_ref_number_present {
// Property name is defined by the reference number.
// This can be a forward reference.
let ref_number = read_unsigned_integer(reader)?; // Reference number to property name.
let property_name = self.m_propnames.get(&ref_number);
trace!("ref_number = {}", ref_number);
// property_name.cloned().ok_or(OASISReadError::PropStringIdNotFound(ref_number))?
match property_name {
Some(name) => NameOrRef::Name(name.clone()),
None => NameOrRef::NameRef(ref_number), // This is a forward reference.
}
} else {
NameOrRef::Name(read_name_string(reader)?)
}
} else {
// Implicit name: Modal variable `last_property_name` is used.
self.modal
.last_property_name
.take()
.ok_or(OASISReadError::ModalLastPropertyNameNotDefined)?
};
let values = if !use_last_value_list {
let num_values = if uuuu == 15 {
read_unsigned_integer(reader)?
} else {
uuuu
};
// Read property values.
let mut prop_value_list = Vec::with_capacity(num_values.min(1 << 20) as usize);
for _i in 0..num_values {
let prop = read_property_value(reader)?;
prop_value_list.push(prop)
}
prop_value_list
} else {
// uuuu must be 0
if uuuu != 0 {
log::error!("The bits 'uuuu' must be 0 but is {}", uuuu);
return Err(OASISReadError::FormatError); // TODO More specific error type: "uuuu must be 0".
}
self.modal
.last_value_list
.take()
.ok_or(OASISReadError::ModalLastValueListNotDefined)?
};
// Update modal variables.
self.modal.last_property_name = Some(property_name_or_ref.clone());
self.modal.last_value_list = Some(values.clone());
(property_name_or_ref, values)
} else {
// Use the last property.
(
self.modal
.last_property_name
.clone()
.ok_or(OASISReadError::ModalLastPropertyNameNotDefined)?,
self.modal
.last_value_list
.clone()
.ok_or(OASISReadError::ModalLastValueListNotDefined)?,
)
};
trace!("property name or reference = {:?}", &property_name_or_ref);
trace!("property values = {:?}", &property_values);
match property_name_or_ref {
NameOrRef::Name(property_name) => {
// Name is known.
trace!("property name = {}", &property_name);
// Store the properties!
Self::set_property(
layout,
&self.property_parent,
&property_name,
&property_values,
&self.m_propstrings,
);
}
NameOrRef::NameRef(property_name_ref) => {
// Forward reference to a property name.
trace!(
"Property name is a forward reference = {}",
&property_name_ref
);
// Remember forward reference to be resolved later.
self.m_property_name_forward_references
.entry(property_name_ref)
.or_default()
.push((self.property_parent.clone(), property_values))
}
}
Ok(())
}
}
/// Read an OASIS layout.
pub fn read_layout<R: Read, L: LayoutEdit<Coord = SInt>>(
reader: &mut R,
layout: &mut L,
) -> Result<(), OASISReadError> {
let reader_state: ReaderState<L> = Default::default();
reader_state.read_layout(reader, layout)
}