Skip to main content

brep_kernel/io/parasolid/
reader.rs

1//! The text transmit reader: header, token stream, embedded-schema deltas and
2//! the node graph (Parasolid XT Format Reference, chapters 2 and 3).
3//!
4//! A text part is a bytestream cut into ~80-character records; the record
5//! breaks carry no meaning, so the reader joins the records and walks one
6//! string. Numbers are followed by one space; `c` (char) and `l` (logical)
7//! fields are single characters with no separator, and the unset value of
8//! an integer, real or vector is a lone `?` with no separator either.
9
10use std::rc::Rc;
11
12use rustc_hash::FxHashMap as HashMap;
13
14use super::schema::{self, Count, FieldDef, Kind};
15
16/// The field layout of one node type as this file writes it.
17#[derive(Debug)]
18pub struct NodeLayout {
19    pub node_type: u16,
20    pub name: String,
21    pub fields: Vec<FieldDef>,
22}
23
24impl NodeLayout {
25    fn variable(&self) -> bool {
26        self.fields.last().is_some_and(|f| f.count == Count::Variable)
27    }
28
29    fn position(&self, name: &str) -> Option<usize> {
30        self.fields.iter().position(|f| f.name == name)
31    }
32}
33
34/// One field value. Unset values (`?`) are `None`.
35#[derive(Clone, Debug, PartialEq)]
36pub enum Value {
37    Int(Option<i64>),
38    Real(Option<f64>),
39    Vector(Option<[f64; 3]>),
40    Interval([Option<f64>; 2]),
41    Box([Option<f64>; 6]),
42    Char(u8),
43    Array(Vec<Value>),
44    Text(String),
45}
46
47/// A node: its type, index and field values in its layout's order.
48#[derive(Debug)]
49pub struct Node {
50    pub index: u32,
51    pub layout: Rc<NodeLayout>,
52    pub values: Vec<Value>,
53}
54
55impl Node {
56    pub fn node_type(&self) -> u16 {
57        self.layout.node_type
58    }
59
60    pub fn type_name(&self) -> &str {
61        &self.layout.name
62    }
63
64    /// A field by name; `None` when this file's layout has no such field.
65    pub fn field(&self, name: &str) -> Option<&Value> {
66        self.layout.position(name).map(|i| &self.values[i])
67    }
68
69    /// An integer or pointer field; unset and absent read as `None`.
70    pub fn int(&self, name: &str) -> Option<i64> {
71        match self.field(name) {
72            Some(Value::Int(v)) => *v,
73            _ => None,
74        }
75    }
76
77    /// A pointer field's index; null, unset and absent read as 0.
78    pub fn ptr(&self, name: &str) -> u32 {
79        self.int(name).filter(|&v| v > 0).map_or(0, |v| v as u32)
80    }
81
82    pub fn real(&self, name: &str) -> Option<f64> {
83        match self.field(name) {
84            Some(Value::Real(v)) => *v,
85            _ => None,
86        }
87    }
88
89    pub fn vector(&self, name: &str) -> Option<[f64; 3]> {
90        match self.field(name) {
91            Some(Value::Vector(v)) => *v,
92            _ => None,
93        }
94    }
95
96    pub fn interval(&self, name: &str) -> Option<[Option<f64>; 2]> {
97        match self.field(name) {
98            Some(Value::Interval(v)) => Some(*v),
99            _ => None,
100        }
101    }
102
103    pub fn char(&self, name: &str) -> Option<u8> {
104        match self.field(name) {
105            Some(Value::Char(c)) => Some(*c),
106            _ => None,
107        }
108    }
109
110    /// A logical field; `T` is true.
111    pub fn logical(&self, name: &str) -> Option<bool> {
112        self.char(name).map(|c| c == b'T')
113    }
114
115    pub fn text(&self, name: &str) -> Option<&str> {
116        match self.field(name) {
117            Some(Value::Text(s)) => Some(s),
118            _ => None,
119        }
120    }
121
122    pub fn array(&self, name: &str) -> &[Value] {
123        match self.field(name) {
124            Some(Value::Array(v)) => v,
125            _ => &[],
126        }
127    }
128
129    /// An array of reals (unset entries as NaN).
130    pub fn reals(&self, name: &str) -> Vec<f64> {
131        self.array(name)
132            .iter()
133            .map(|v| match v {
134                Value::Real(Some(x)) => *x,
135                _ => f64::NAN,
136            })
137            .collect()
138    }
139
140    /// An array of integers or pointers (unset entries as 0).
141    pub fn ints(&self, name: &str) -> Vec<i64> {
142        self.array(name)
143            .iter()
144            .map(|v| match v {
145                Value::Int(Some(x)) => *x,
146                _ => 0,
147            })
148            .collect()
149    }
150
151    /// An array of vectors (unset entries as `None`).
152    pub fn vectors(&self, name: &str) -> Vec<Option<[f64; 3]>> {
153        self.array(name)
154            .iter()
155            .map(|v| match v {
156                Value::Vector(x) => *x,
157                _ => None,
158            })
159            .collect()
160    }
161}
162
163/// A parsed text transmit file.
164#[derive(Debug)]
165pub struct XtFile {
166    /// `TRANSMIT FILE created by modeller version …`.
167    pub modeller_version: String,
168    /// `SCH_<version>_<schema>[_<base>]`.
169    pub schema: String,
170    /// The header's `KEY=value` pairs (parts 1 to 3).
171    pub header: Vec<(String, String)>,
172    nodes: Vec<Node>,
173    by_index: HashMap<u32, usize>,
174}
175
176impl XtFile {
177    /// The root node: the first node in the file (§2.1).
178    pub fn root(&self) -> Option<&Node> {
179        self.nodes.first()
180    }
181
182    pub fn nodes(&self) -> &[Node] {
183        &self.nodes
184    }
185
186    /// The node an index names; 0 and indices with no node are null (§2.1.4.4).
187    pub fn node(&self, index: u32) -> Option<&Node> {
188        if index == 0 {
189            return None;
190        }
191        self.by_index.get(&index).map(|&i| &self.nodes[i])
192    }
193
194    /// The node a pointer field of `node` names.
195    pub fn follow(&self, node: &Node, field: &str) -> Option<&Node> {
196        self.node(node.ptr(field))
197    }
198
199    pub fn header_value(&self, key: &str) -> Option<&str> {
200        self.header.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
201    }
202}
203
204/// Unset integer and real values as written by binary writers; text writes `?`.
205const NULL_INT: i64 = -32764;
206
207/// Read a text transmit file (`.x_t`, `.xmt_txt`).
208pub fn parse_xt_text(text: &str) -> Result<XtFile, String> {
209    let bytes = text.as_bytes();
210    if bytes.starts_with(b"PS") {
211        return Err("this is a binary Parasolid file (.x_b); only text .x_t files are read".into());
212    }
213    let (header, body_start) = split_header(text);
214    let data = join_records(&text[body_start..]);
215    let mut stream = Stream { data: &data, at: 0 };
216    stream.skip_blank();
217    match stream.next_byte() {
218        Some(b'T') => {}
219        Some(b'P' | b'B') => {
220            return Err("this is a binary Parasolid file (.x_b); only text .x_t files are read".into())
221        }
222        other => {
223            return Err(format!(
224                "not a Parasolid text transmit file: the part data starts with {:?}, expected 'T'",
225                other.map(char::from)
226            ))
227        }
228    }
229    let modeller_version = stream.string()?;
230    if modeller_version.contains("(partition)") {
231        return Err("this is a Parasolid partition file; only part files are read".into());
232    }
233    let schema_name = stream.string()?;
234    // `SCH_1400068_14000_13006`: the base suffix marks embedded schema deltas,
235    // followed by the maximum node type (§2.1.2.2).
236    let embedded = schema_name.split('_').count() >= 4;
237    if embedded {
238        let base = schema_name.rsplit('_').next().unwrap_or_default();
239        if base != schema::BASE_SCHEMA {
240            return Err(format!(
241                "the file's schema {schema_name} is relative to base {base}; only base {} is known",
242                schema::BASE_SCHEMA
243            ));
244        }
245        stream.int()?;
246    }
247    // Without embedded deltas the layouts are the named schema's own: the
248    // base's, or a stored schema's.
249    let stored = if embedded {
250        None
251    } else {
252        schema::STORED_SCHEMAS.into_iter().find(|s| schema_name.ends_with(&format!("_{s}")))
253    };
254    if !embedded && stored.is_none() && !schema_name.ends_with(&format!("_{}", schema::BASE_SCHEMA)) {
255        return Err(format!(
256            "the file's schema {schema_name} carries no description of its layout; only files written with schema {} \
257             or {}, or with embedded schema deltas (Parasolid V14 and later), are read",
258            schema::BASE_SCHEMA,
259            schema::STORED_SCHEMAS.join(", ")
260        ));
261    }
262    let user_field_size = stream.int()?.unwrap_or(0).max(0) as usize;
263    let mut layouts: HashMap<u16, Rc<NodeLayout>> = HashMap::default();
264    let mut nodes = Vec::new();
265    let mut by_index = HashMap::default();
266    loop {
267        let at = stream.at;
268        let node_type = stream.int()?.ok_or("a node type is unset")?;
269        if node_type == 1 {
270            // Terminator: type 1, index 0.
271            if stream.int()? == Some(0) {
272                break;
273            }
274            return Err(format!("node type 1 at byte {at} is not followed by the terminating 0"));
275        }
276        let node_type = u16::try_from(node_type).map_err(|_| format!("node type {node_type} at byte {at} is out of range"))?;
277        let layout = match layouts.get(&node_type) {
278            Some(layout) => layout.clone(),
279            None => {
280                let layout = Rc::new(if embedded {
281                    read_layout(&mut stream, node_type)?
282                } else if let Some(stored) = stored {
283                    stored_layout(stored, node_type)?
284                } else {
285                    base_layout(node_type)?
286                });
287                layouts.insert(node_type, layout.clone());
288                layout
289            }
290        };
291        let node = read_node(&mut stream, layout, user_field_size)
292            .map_err(|e| format!("node type {node_type} at byte {at}: {e}"))?;
293        if by_index.insert(node.index, nodes.len()).is_some() {
294            return Err(format!("node index {} appears twice", node.index));
295        }
296        nodes.push(node);
297    }
298    if nodes.is_empty() {
299        return Err("the file holds no nodes".into());
300    }
301    Ok(XtFile { modeller_version, schema: schema_name, header, nodes, by_index })
302}
303
304fn base_layout(node_type: u16) -> Result<NodeLayout, String> {
305    let (name, fields) = schema::base(node_type)
306        .ok_or_else(|| format!("node type {node_type} is not in the base schema and the file does not describe it"))?;
307    Ok(NodeLayout { node_type, name: name.to_string(), fields })
308}
309
310/// A node type's layout in a stored schema; a type no file in that schema
311/// has shown is refused by name.
312fn stored_layout(stored: &str, node_type: u16) -> Result<NodeLayout, String> {
313    let delta = schema::stored_delta(stored, node_type).ok_or_else(|| {
314        let name = schema::base(node_type).map_or_else(|| format!("node type {node_type}"), |(n, _)| format!("node type {node_type} ({n})"));
315        format!("{name} has no known layout in schema {stored} and the file does not describe it")
316    })?;
317    read_layout(&mut Stream { data: delta.as_bytes(), at: 0 }, node_type)
318        .map_err(|e| format!("the stored schema {stored} layout of node type {node_type}: {e}"))
319}
320
321/// A node type's layout from its first occurrence (§2.1.2.2): 255 for "as the
322/// base", a new type's full description, or an edit script against the base.
323fn read_layout(stream: &mut Stream, node_type: u16) -> Result<NodeLayout, String> {
324    let count = stream.int()?.ok_or("a field count is unset")?;
325    // A field count is a byte (§2.1.2.2); 255 means "as the base".
326    if !(0..=255).contains(&count) {
327        return Err(format!("node type {node_type} declares {count} fields"));
328    }
329    let Some((name, base)) = schema::base(node_type) else {
330        // A type the base schema does not have: its whole description.
331        let name = stream.string()?;
332        let _description = stream.string()?;
333        let mut fields = Vec::with_capacity(count.max(0) as usize);
334        for _ in 0..count {
335            fields.push(stream.field_def()?);
336        }
337        return Ok(NodeLayout { node_type, name, fields });
338    };
339    if count == 255 {
340        return Ok(NodeLayout { node_type, name: name.to_string(), fields: base });
341    }
342    let mut fields = Vec::with_capacity(count.max(0) as usize);
343    let mut base_fields = base.into_iter();
344    loop {
345        match stream.next_byte() {
346            Some(b'C') => fields.push(
347                base_fields
348                    .next()
349                    .ok_or_else(|| format!("{name}'s schema copies past the end of the base layout"))?,
350            ),
351            Some(b'D') => {
352                base_fields
353                    .next()
354                    .ok_or_else(|| format!("{name}'s schema deletes past the end of the base layout"))?;
355            }
356            Some(b'I' | b'A') => fields.push(stream.field_def()?),
357            Some(b'Z') => break,
358            other => {
359                return Err(format!(
360                    "{name}'s schema edit has instruction {:?}, expected C, D, I, A or Z",
361                    other.map(char::from)
362                ))
363            }
364        }
365    }
366    if fields.len() as i64 != count {
367        return Err(format!("{name}'s schema edit gives {} fields, its header says {count}", fields.len()));
368    }
369    Ok(NodeLayout { node_type, name: name.to_string(), fields })
370}
371
372/// Node types visible at the PK interface, which carry the user field (§2.1, §6.1).
373fn carries_user_field(node_type: u16) -> bool {
374    matches!(
375        node_type,
376        10..=19 | 29..=32 | 38 | 50..=54 | 56 | 60 | 67 | 68 | 70 | 80 | 81 | 90 | 100 | 120 | 124 | 130 | 133
377            | 134 | 137 | 200 | 201 | 222
378    )
379}
380
381fn read_node(stream: &mut Stream, layout: Rc<NodeLayout>, user_field_size: usize) -> Result<Node, String> {
382    let length = if layout.variable() {
383        let n = stream.int()?.ok_or("a variable length is unset")?;
384        let n = usize::try_from(n).map_err(|_| format!("variable length {n} is negative"))?;
385        // Every element takes at least one byte of the data.
386        if n > stream.remaining() {
387            return Err(format!("variable length {n} runs past the end of the data"));
388        }
389        n
390    } else {
391        0
392    };
393    let index = stream.int()?.ok_or("a node index is unset")?;
394    let index = u32::try_from(index).ok().filter(|&i| i > 0).ok_or_else(|| format!("node index {index} is invalid"))?;
395    let mut values = Vec::with_capacity(layout.fields.len());
396    for field in &layout.fields {
397        let value = match field.count {
398            Count::Scalar => stream.value(field.kind),
399            Count::Variable if matches!(field.kind, Kind::Char) => stream.chars(length).map(Value::Text),
400            Count::Variable => (0..length).map(|_| stream.value(field.kind)).collect::<Result<_, _>>().map(Value::Array),
401            Count::Fixed(n) => (0..n).map(|_| stream.value(field.kind)).collect::<Result<_, _>>().map(Value::Array),
402        }
403        .map_err(|e| format!("{} field {}: {e}", layout.name, field.name))?;
404        values.push(value);
405    }
406    if layout.node_type < 1000 && carries_user_field(layout.node_type) {
407        for _ in 0..user_field_size {
408            stream.int()?;
409        }
410    }
411    Ok(Node { index, layout, values })
412}
413
414/// The header's `KEY=value;` pairs and where the part data starts (§3.1). A
415/// file with no header starts with its part data.
416fn split_header(text: &str) -> (Vec<(String, String)>, usize) {
417    let Some(end) = text.find("**END_OF_HEADER") else {
418        return (Vec::new(), 0);
419    };
420    let body_start = text[end..].find('\n').map_or(text.len(), |n| end + n + 1);
421    let mut joined = String::new();
422    for line in text[..end].lines() {
423        let line = line.trim_end_matches('\r');
424        if line.starts_with("**ABCDEFG") || line.starts_with("**PARASOLID") {
425            continue;
426        }
427        joined.push_str(line);
428    }
429    let mut header = Vec::new();
430    for item in joined.split(';') {
431        let item = item.trim_start_matches(|c| c == '*').trim();
432        let item = item.strip_prefix("PART1").or_else(|| item.strip_prefix("PART2")).or_else(|| item.strip_prefix("PART3")).unwrap_or(item);
433        let item = item.trim_start_matches(|c| c == '*' || c == ';');
434        if let Some((key, value)) = item.split_once('=') {
435            header.push((key.trim().to_string(), unescape_header(value)));
436        }
437    }
438    (header, body_start)
439}
440
441/// §3.1.1 keyword escapes.
442fn unescape_header(value: &str) -> String {
443    let mut out = String::with_capacity(value.len());
444    let mut chars = value.chars();
445    while let Some(c) = chars.next() {
446        if c != '^' {
447            out.push(c);
448            continue;
449        }
450        match chars.next() {
451            Some('n') => out.push('\n'),
452            Some('-') => out.push(' '),
453            Some(';') => out.push(';'),
454            Some('^') => out.push('^'),
455            Some(other) => {
456                out.push('^');
457                out.push(other);
458            }
459            None => out.push('^'),
460        }
461    }
462    out
463}
464
465/// §3.2: record breaks, carriage returns and the trailing spaces a system may
466/// add to a record are not part of the data; leading spaces are.
467fn join_records(text: &str) -> Vec<u8> {
468    let mut data = Vec::with_capacity(text.len());
469    for line in text.split('\n') {
470        data.extend_from_slice(line.trim_end_matches(['\r', ' ']).as_bytes());
471    }
472    data
473}
474
475struct Stream<'a> {
476    data: &'a [u8],
477    at: usize,
478}
479
480impl Stream<'_> {
481    fn skip_blank(&mut self) {
482        while self.at < self.data.len() && self.data[self.at].is_ascii_whitespace() {
483            self.at += 1;
484        }
485    }
486
487    fn remaining(&self) -> usize {
488        self.data.len().saturating_sub(self.at)
489    }
490
491    fn peek(&self) -> Option<u8> {
492        self.data.get(self.at).copied()
493    }
494
495    fn next_byte(&mut self) -> Option<u8> {
496        let b = self.peek()?;
497        self.at += 1;
498        Some(b)
499    }
500
501    /// A space-terminated token.
502    fn token(&mut self) -> Result<&str, String> {
503        let start = self.at;
504        while self.at < self.data.len() && self.data[self.at] != b' ' {
505            self.at += 1;
506        }
507        let token = &self.data[start..self.at];
508        if self.at < self.data.len() {
509            self.at += 1;
510        }
511        if token.is_empty() {
512            return Err(if start >= self.data.len() {
513                "the data ends before the terminator".into()
514            } else {
515                format!("an empty token at byte {start}")
516            });
517        }
518        std::str::from_utf8(token).map_err(|_| format!("a non-text token at byte {start}"))
519    }
520
521    /// An integer, or `None` for `?`.
522    fn int(&mut self) -> Result<Option<i64>, String> {
523        if self.peek() == Some(b'?') {
524            self.at += 1;
525            return Ok(None);
526        }
527        let at = self.at;
528        let token = self.token()?;
529        let value: i64 = token.parse().map_err(|_| format!("expected an integer at byte {at}, read {token:?}"))?;
530        Ok((value != NULL_INT).then_some(value))
531    }
532
533    /// A real, or `None` for `?`.
534    fn real(&mut self) -> Result<Option<f64>, String> {
535        if self.peek() == Some(b'?') {
536            self.at += 1;
537            return Ok(None);
538        }
539        let at = self.at;
540        let token = self.token()?;
541        let value: f64 = token.parse().map_err(|_| format!("expected a real at byte {at}, read {token:?}"))?;
542        if !value.is_finite() {
543            return Err(format!("a non-finite real at byte {at}"));
544        }
545        // The null real, -3.14158e13, marks an unset value in binary writers.
546        Ok((value != -3.14158e13).then_some(value))
547    }
548
549    fn vector(&mut self) -> Result<Option<[f64; 3]>, String> {
550        // One `?` stands for a whole unset vector (§3.2).
551        if self.peek() == Some(b'?') {
552            self.at += 1;
553            return Ok(None);
554        }
555        let (x, y, z) = (self.real()?, self.real()?, self.real()?);
556        Ok(match (x, y, z) {
557            (Some(x), Some(y), Some(z)) => Some([x, y, z]),
558            _ => None,
559        })
560    }
561
562    fn value(&mut self, kind: Kind) -> Result<Value, String> {
563        Ok(match kind {
564            Kind::Int => Value::Int(self.int()?),
565            Kind::Real => Value::Real(self.real()?),
566            Kind::Vector => Value::Vector(self.vector()?),
567            // Like a vector, an unset interval or box is one `?`.
568            Kind::Interval | Kind::Box if self.peek() == Some(b'?') => {
569                self.at += 1;
570                match kind {
571                    Kind::Interval => Value::Interval([None; 2]),
572                    _ => Value::Box([None; 6]),
573                }
574            }
575            Kind::Interval => Value::Interval([self.real()?, self.real()?]),
576            Kind::Box => {
577                let mut out = [None; 6];
578                for v in &mut out {
579                    *v = self.real()?;
580                }
581                Value::Box(out)
582            }
583            Kind::Char => Value::Char(self.next_byte().ok_or("the data ends inside a character field")?),
584            Kind::Unknown => {
585                return Err("the base schema layout of this field is not known (it is deleted in every schema seen)".into())
586            }
587        })
588    }
589
590    /// A short string: its length, a space, then the characters (§2.1.2.1).
591    fn string(&mut self) -> Result<String, String> {
592        let n = self.int()?.ok_or("a string length is unset")?;
593        let n = usize::try_from(n).map_err(|_| format!("string length {n} is negative"))?;
594        if n > self.remaining() {
595            return Err(format!("string length {n} runs past the end of the data"));
596        }
597        self.chars(n)
598    }
599
600    /// `n` characters of a char field, with the §3.2 and §2.1.3 escapes
601    /// (`\0`, `\n`, `\r`, `\\`, and `\<d>` for d spaces) each counting as the
602    /// characters they stand for.
603    fn chars(&mut self, n: usize) -> Result<String, String> {
604        let mut out = Vec::with_capacity(n);
605        while out.len() < n {
606            let b = self.next_byte().ok_or("the data ends inside a string")?;
607            if b != b'\\' {
608                out.push(b);
609                continue;
610            }
611            match self.next_byte() {
612                Some(b'0') => out.push(0),
613                Some(b'n') => out.push(b'\n'),
614                Some(b'r') => out.push(b'\r'),
615                Some(b'\\') => out.push(b'\\'),
616                Some(d @ b'1'..=b'9') => out.extend(std::iter::repeat(b' ').take(usize::from(d - b'0'))),
617                Some(other) => {
618                    out.push(b'\\');
619                    out.push(other);
620                }
621                None => return Err("the data ends inside a string escape".into()),
622            }
623        }
624        out.truncate(n);
625        Ok(String::from_utf8_lossy(&out).into_owned())
626    }
627
628    /// A field description in a schema delta (§2.1.2.2): name, pointer class,
629    /// element count, type (when not a pointer), transmit flag (when variable).
630    fn field_def(&mut self) -> Result<FieldDef, String> {
631        let name = self.string()?;
632        let pointer_class = self.int()?.unwrap_or(0);
633        let elements = self.int()?.ok_or("a field's element count is unset")?;
634        let kind = if pointer_class != 0 {
635            Kind::Int
636        } else {
637            let code = self.string()?;
638            let code = code.bytes().next().ok_or_else(|| format!("field {name} has an empty type"))?;
639            schema::kind_of(code).ok_or_else(|| format!("field {name} has unknown type {:?}", char::from(code)))?
640        };
641        if elements == 1 {
642            self.next_byte().ok_or("the data ends inside a field description")?;
643        }
644        let count = match elements {
645            0 => Count::Scalar,
646            1 => Count::Variable,
647            n if n > 1 && (n as u64) <= self.remaining() as u64 => Count::Fixed(n as usize),
648            n => return Err(format!("field {name} has element count {n}")),
649        };
650        Ok(FieldDef { name, kind, count })
651    }
652}