threers 0.0.7

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
//! ISO 10303-21 — the STEP physical file.
//!
//! The exchange syntax only, with no opinion about what the entities mean: a
//! file is a header and a list of `#id = NAME(args);` instances, and an argument
//! is a reference, a number, a string, an enum, a list, or one of the two
//! placeholders. What those entities *say* is AP203/AP214, and that lives in
//! [`mod@super::export`] and [`mod@super::import`].
//!
//! Keeping the split sharp is worth it: nearly every real-world STEP problem is
//! a lexical one — a real written without its decimal point, a name with a
//! quote in it, a `-0.` where a reader expected an integer — and those are
//! findable here, against a round-trip, without constructing any geometry.

use std::collections::HashMap;
use std::fmt::Write as _;

/// One argument of an entity instance.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// `#42` — a reference to another instance.
    Ref(u64),
    Int(i64),
    Real(f64),
    /// `'text'`, already unescaped.
    Text(String),
    /// `.T.`, `.CARTESIAN.` — held without the dots.
    Enum(String),
    /// `"0F3A"` — a binary literal, held as its hex digits.
    Binary(String),
    List(Vec<Value>),
    /// `NAME(args)` appearing as an argument, which is how a SELECT type that
    /// needs naming, or a nested constructor, is written.
    Typed(String, Vec<Value>),
    /// `$` — unset.
    Omitted,
    /// `*` — inherited from a supertype and not restated.
    Derived,
}

impl Value {
    /// The referenced id, for the common case of an argument that must be one.
    pub fn as_ref(&self) -> Option<u64> {
        match self {
            Value::Ref(id) => Some(*id),
            _ => None,
        }
    }

    /// A number, accepting an integer where a real is expected.
    ///
    /// STEP requires reals to carry a decimal point, so `1` and `1.` are
    /// formally different tokens. Readers that enforce that reject a great many
    /// files in the wild; this accepts both and writes the correct one.
    pub fn as_real(&self) -> Option<f64> {
        match self {
            Value::Real(x) => Some(*x),
            Value::Int(i) => Some(*i as f64),
            _ => None,
        }
    }

    pub fn as_int(&self) -> Option<i64> {
        match self {
            Value::Int(i) => Some(*i),
            _ => None,
        }
    }

    pub fn as_text(&self) -> Option<&str> {
        match self {
            Value::Text(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_list(&self) -> Option<&[Value]> {
        match self {
            Value::List(v) => Some(v),
            _ => None,
        }
    }

    /// `.T.` / `.F.`, the STEP spelling of a boolean.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Enum(e) if e == "T" => Some(true),
            Value::Enum(e) if e == "F" => Some(false),
            _ => None,
        }
    }
}

/// One `#id = NAME(args);` instance.
///
/// A *complex* instance — `#1 = (A(..) B(..));`, which AP203 uses for the
/// rational B-spline surfaces and for units — has an empty `name` and carries
/// its parts as [`Value::Typed`] in `args`.
#[derive(Debug, Clone, PartialEq)]
pub struct Entity {
    pub id: u64,
    pub name: String,
    pub args: Vec<Value>,
}

impl Entity {
    /// The part of a complex instance with this name, or the whole entity if it
    /// is simple and named that.
    pub fn part(&self, name: &str) -> Option<&[Value]> {
        if self.name == name {
            return Some(&self.args);
        }
        self.args.iter().find_map(|a| match a {
            Value::Typed(n, args) if n == name => Some(&args[..]),
            _ => None,
        })
    }

    /// Whether a simple or complex instance carries this name at all.
    pub fn is(&self, name: &str) -> bool {
        self.part(name).is_some()
    }
}

/// A parsed exchange file.
#[derive(Debug, Clone, Default)]
pub struct StepFile {
    /// Header instances (`FILE_DESCRIPTION`, `FILE_NAME`, `FILE_SCHEMA`), which
    /// are unnumbered in the file and given sequential ids here.
    pub header: Vec<Entity>,
    pub data: Vec<Entity>,
}

impl StepFile {
    /// Index the data section by id.
    pub fn index(&self) -> HashMap<u64, &Entity> {
        self.data.iter().map(|e| (e.id, e)).collect()
    }

    /// Every data instance carrying `name`, in file order.
    pub fn all<'s>(&'s self, name: &'s str) -> impl Iterator<Item = &'s Entity> + 's {
        self.data.iter().filter(move |e| e.is(name))
    }
}

/// Why a file could not be read.
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    pub message: String,
    /// Byte offset into the input, for pointing at the problem.
    pub at: usize,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} at byte {}", self.message, self.at)
    }
}

impl std::error::Error for ParseError {}

// --------------------------------------------------------------------------
// Reading
// --------------------------------------------------------------------------

struct Parser<'a> {
    s: &'a [u8],
    i: usize,
}

impl<'a> Parser<'a> {
    fn err<T>(&self, message: impl Into<String>) -> Result<T, ParseError> {
        Err(ParseError {
            message: message.into(),
            at: self.i,
        })
    }

    /// Whitespace and `/* */` comments.
    fn space(&mut self) {
        loop {
            while self.i < self.s.len() && self.s[self.i].is_ascii_whitespace() {
                self.i += 1;
            }
            if self.s[self.i..].starts_with(b"/*") {
                match find(&self.s[self.i + 2..], b"*/") {
                    Some(n) => self.i += 2 + n + 2,
                    None => {
                        self.i = self.s.len();
                        return;
                    }
                }
            } else {
                return;
            }
        }
    }

    fn eat(&mut self, word: &[u8]) -> bool {
        self.space();
        // Keywords are case-insensitive in practice, and files written by hand
        // are not consistent about it.
        if self.s.len() >= self.i + word.len()
            && self.s[self.i..self.i + word.len()].eq_ignore_ascii_case(word)
        {
            self.i += word.len();
            true
        } else {
            false
        }
    }

    fn expect(&mut self, word: &[u8]) -> Result<(), ParseError> {
        if self.eat(word) {
            Ok(())
        } else {
            self.err(format!("expected `{}`", String::from_utf8_lossy(word)))
        }
    }

    fn peek(&mut self) -> Option<u8> {
        self.space();
        self.s.get(self.i).copied()
    }

    fn name(&mut self) -> Result<String, ParseError> {
        self.space();
        let start = self.i;
        while self.i < self.s.len()
            && (self.s[self.i].is_ascii_alphanumeric() || self.s[self.i] == b'_')
        {
            self.i += 1;
        }
        if self.i == start {
            return self.err("expected an entity name");
        }
        Ok(String::from_utf8_lossy(&self.s[start..self.i]).to_ascii_uppercase())
    }

    fn value(&mut self) -> Result<Value, ParseError> {
        match self.peek() {
            None => self.err("unexpected end of file"),
            Some(b'$') => {
                self.i += 1;
                Ok(Value::Omitted)
            }
            Some(b'*') => {
                self.i += 1;
                Ok(Value::Derived)
            }
            Some(b'#') => {
                self.i += 1;
                let start = self.i;
                while self.i < self.s.len() && self.s[self.i].is_ascii_digit() {
                    self.i += 1;
                }
                if self.i == start {
                    return self.err("expected a digit after `#`");
                }
                let text = std::str::from_utf8(&self.s[start..self.i]).unwrap_or("");
                match text.parse() {
                    Ok(id) => Ok(Value::Ref(id)),
                    Err(_) => self.err("instance id out of range"),
                }
            }
            Some(b'\'') => Ok(Value::Text(self.text()?)),
            Some(b'"') => {
                self.i += 1;
                let start = self.i;
                while self.i < self.s.len() && self.s[self.i] != b'"' {
                    self.i += 1;
                }
                let hex = String::from_utf8_lossy(&self.s[start..self.i]).to_string();
                if self.i >= self.s.len() {
                    return self.err("unterminated binary literal");
                }
                self.i += 1;
                Ok(Value::Binary(hex))
            }
            Some(b'.') => {
                self.i += 1;
                let start = self.i;
                while self.i < self.s.len() && self.s[self.i] != b'.' {
                    self.i += 1;
                }
                let e = String::from_utf8_lossy(&self.s[start..self.i]).to_string();
                if self.i >= self.s.len() {
                    return self.err("unterminated enumeration");
                }
                self.i += 1;
                Ok(Value::Enum(e))
            }
            Some(b'(') => {
                self.i += 1;
                Ok(Value::List(self.args(b')')?))
            }
            Some(c) if c.is_ascii_digit() || c == b'-' || c == b'+' => self.number(),
            Some(c) if c.is_ascii_alphabetic() || c == b'_' || c == b'!' => {
                if self.s[self.i] == b'!' {
                    self.i += 1; // a user-defined entity name
                }
                let name = self.name()?;
                self.expect(b"(")?;
                Ok(Value::Typed(name, self.args(b')')?))
            }
            Some(c) => self.err(format!("unexpected `{}`", c as char)),
        }
    }

    /// A string literal, with `''` unescaped and `\X2\..\X0\` decoded.
    fn text(&mut self) -> Result<String, ParseError> {
        self.i += 1; // opening quote
        let mut raw = String::new();
        loop {
            let Some(&c) = self.s.get(self.i) else {
                return self.err("unterminated string");
            };
            self.i += 1;
            if c == b'\'' {
                if self.s.get(self.i) == Some(&b'\'') {
                    self.i += 1;
                    raw.push('\'');
                    continue;
                }
                break;
            }
            raw.push(c as char);
        }
        Ok(decode_control_directives(&raw))
    }

    fn number(&mut self) -> Result<Value, ParseError> {
        let start = self.i;
        if matches!(self.s.get(self.i), Some(b'-') | Some(b'+')) {
            self.i += 1;
        }
        let mut real = false;
        while let Some(&c) = self.s.get(self.i) {
            if c.is_ascii_digit() {
                self.i += 1;
            } else if c == b'.' {
                real = true;
                self.i += 1;
            } else if c == b'e' || c == b'E' {
                real = true;
                self.i += 1;
                if matches!(self.s.get(self.i), Some(b'-') | Some(b'+')) {
                    self.i += 1;
                }
            } else {
                break;
            }
        }
        let text = String::from_utf8_lossy(&self.s[start..self.i]).to_string();
        if real {
            // `1.E-3` and `1.` are legal STEP but not legal Rust; patch the
            // missing mantissa digit before parsing.
            let patched = text.replace(".E", ".0E").replace(".e", ".0e");
            let patched = if patched.ends_with('.') {
                format!("{patched}0")
            } else {
                patched
            };
            match patched.parse() {
                Ok(x) => Ok(Value::Real(x)),
                Err(_) => self.err(format!("`{text}` is not a real")),
            }
        } else {
            match text.parse() {
                Ok(i) => Ok(Value::Int(i)),
                Err(_) => self.err(format!("`{text}` is not an integer")),
            }
        }
    }

    /// Comma-separated values up to `close`, which is consumed.
    fn args(&mut self, close: u8) -> Result<Vec<Value>, ParseError> {
        let mut out = Vec::new();
        if self.peek() == Some(close) {
            self.i += 1;
            return Ok(out);
        }
        loop {
            out.push(self.value()?);
            match self.peek() {
                Some(b',') => self.i += 1,
                Some(c) if c == close => {
                    self.i += 1;
                    return Ok(out);
                }
                None => return self.err("unterminated argument list"),
                Some(c) => return self.err(format!("expected `,` or `)`, found `{}`", c as char)),
            }
        }
    }

    /// One instance, or `None` at `ENDSEC;`.
    fn instance(&mut self, next_header_id: &mut u64) -> Result<Option<Entity>, ParseError> {
        if self.peek().is_none() || self.eat(b"ENDSEC") {
            let _ = self.eat(b";");
            return Ok(None);
        }
        let id = if self.peek() == Some(b'#') {
            self.i += 1;
            let start = self.i;
            while self.i < self.s.len() && self.s[self.i].is_ascii_digit() {
                self.i += 1;
            }
            let text = std::str::from_utf8(&self.s[start..self.i]).unwrap_or("");
            let Ok(id) = text.parse::<u64>() else {
                return self.err("instance id out of range");
            };
            self.expect(b"=")?;
            id
        } else {
            // A header instance, which has no id of its own.
            *next_header_id += 1;
            *next_header_id
        };

        let entity = if self.peek() == Some(b'(') {
            // Complex instance: `(A(..) B(..))`, whitespace-separated.
            self.i += 1;
            let mut parts = Vec::new();
            loop {
                match self.peek() {
                    Some(b')') => {
                        self.i += 1;
                        break;
                    }
                    Some(b',') => self.i += 1,
                    None => return self.err("unterminated complex instance"),
                    _ => {
                        let name = self.name()?;
                        self.expect(b"(")?;
                        parts.push(Value::Typed(name, self.args(b')')?));
                    }
                }
            }
            Entity {
                id,
                name: String::new(),
                args: parts,
            }
        } else {
            let name = self.name()?;
            self.expect(b"(")?;
            let args = self.args(b')')?;
            Entity { id, name, args }
        };
        self.expect(b";")?;
        Ok(Some(entity))
    }
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Decode the `\X2\....\X0\` and `\X\hh` control directives of ISO 10303-21.
///
/// Only the ones that carry text: `\X2\` is UTF-16BE, which is how every writer
/// spells a non-ASCII character, and `\X\` is a single Latin-1 byte.
fn decode_control_directives(raw: &str) -> String {
    if !raw.contains('\\') {
        return raw.to_string();
    }
    let b: Vec<char> = raw.chars().collect();
    let mut out = String::with_capacity(raw.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] != '\\' {
            out.push(b[i]);
            i += 1;
            continue;
        }
        let rest: String = b[i..].iter().collect();
        if rest.starts_with("\\X2\\") {
            let mut j = i + 4;
            let mut units: Vec<u16> = Vec::new();
            while j + 3 < b.len() {
                let quad: String = b[j..j + 4].iter().collect();
                let Ok(u) = u16::from_str_radix(&quad, 16) else {
                    break;
                };
                units.push(u);
                j += 4;
            }
            out.push_str(&String::from_utf16_lossy(&units));
            let tail: String = b[j..].iter().collect();
            i = if tail.starts_with("\\X0\\") { j + 4 } else { j };
        } else if rest.starts_with("\\X\\") && i + 5 <= b.len() {
            let pair: String = b[i + 3..i + 5].iter().collect();
            match u8::from_str_radix(&pair, 16) {
                Ok(byte) => out.push(byte as char),
                Err(_) => out.push('\\'),
            }
            i += 5;
        } else {
            out.push('\\');
            i += 1;
        }
    }
    out
}

/// Parse an exchange file.
pub fn parse(input: &str) -> Result<StepFile, ParseError> {
    let mut p = Parser {
        s: input.as_bytes(),
        i: 0,
    };
    // The magic line is expected but not required: files trimmed of it are
    // common enough, and rejecting them buys nothing.
    let _ = p.eat(b"ISO-10303-21") && p.eat(b";");

    let mut file = StepFile::default();
    let mut header_id = 0;
    if p.eat(b"HEADER") {
        p.expect(b";")?;
        while let Some(e) = p.instance(&mut header_id)? {
            file.header.push(e);
        }
    }
    if p.eat(b"DATA") {
        p.expect(b";")?;
        // `DATA` may carry a parameter list, `DATA(#1)`, which is legal and
        // which nothing here needs.
        while let Some(e) = p.instance(&mut header_id)? {
            file.data.push(e);
        }
    }
    let _ = p.eat(b"END-ISO-10303-21") && p.eat(b";");
    Ok(file)
}

// --------------------------------------------------------------------------
// Writing
// --------------------------------------------------------------------------

/// Format a real the way STEP requires: always with a decimal point, never in a
/// form that reads back as an integer.
///
/// `{}` on an f64 gives `1` for 1.0, which is a *different token* — an integer
/// where the schema wants a real. Readers that enforce the distinction reject
/// the file, so this is not cosmetic.
pub fn real(x: f64) -> String {
    if !x.is_finite() {
        // No spelling for these exists in the exchange syntax. Zero is the
        // least destructive stand-in, and callers should not be producing them.
        return "0.".to_string();
    }
    let mut s = format!("{x:?}"); // shortest round-tripping form
    if !s.contains('.') && !s.contains('e') && !s.contains('E') {
        s.push('.');
    }
    // `{:?}` gives `1.0`, which is legal but not what a STEP writer emits; the
    // canonical spelling drops the trailing zero.
    if let Some(head) = s.strip_suffix(".0") {
        s = format!("{head}.");
    }
    // `1e-7` round-trips but has no decimal point in its mantissa.
    if let Some(pos) = s.find(['e', 'E']) {
        if !s[..pos].contains('.') {
            s.insert(pos, '.');
        }
    }
    s
}

/// Escape a string for the exchange syntax.
fn quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        match c {
            '\'' => out.push_str("''"),
            '\\' => out.push_str("\\\\"),
            c if c.is_ascii() && !c.is_control() => out.push(c),
            c => {
                // Anything outside ASCII goes through the UTF-16 directive,
                // which is the only portable spelling.
                out.push_str("\\X2\\");
                let mut buf = [0u16; 2];
                for unit in c.encode_utf16(&mut buf) {
                    let _ = write!(out, "{unit:04X}");
                }
                out.push_str("\\X0\\");
            }
        }
    }
    out.push('\'');
    out
}

impl Value {
    fn write(&self, out: &mut String) {
        match self {
            Value::Ref(id) => {
                let _ = write!(out, "#{id}");
            }
            Value::Int(i) => {
                let _ = write!(out, "{i}");
            }
            Value::Real(x) => out.push_str(&real(*x)),
            Value::Text(s) => out.push_str(&quote(s)),
            Value::Enum(e) => {
                let _ = write!(out, ".{e}.");
            }
            Value::Binary(h) => {
                let _ = write!(out, "\"{h}\"");
            }
            Value::Omitted => out.push('$'),
            Value::Derived => out.push('*'),
            Value::List(v) => {
                out.push('(');
                for (i, x) in v.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    x.write(out);
                }
                out.push(')');
            }
            Value::Typed(name, args) => {
                out.push_str(name);
                out.push('(');
                for (i, x) in args.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    x.write(out);
                }
                out.push(')');
            }
        }
    }
}

impl Entity {
    fn write(&self, out: &mut String, with_id: bool) {
        if with_id {
            let _ = write!(out, "#{}=", self.id);
        }
        if self.name.is_empty() {
            // Complex instance: the parts are juxtaposed, not comma-separated.
            out.push('(');
            for a in &self.args {
                a.write(out);
            }
            out.push(')');
        } else {
            out.push_str(&self.name);
            out.push('(');
            for (i, a) in self.args.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                a.write(out);
            }
            out.push(')');
        }
        out.push_str(";\n");
    }
}

impl StepFile {
    /// Serialise back to an exchange file.
    ///
    /// Named for what it produces rather than as an inherent `to_string`, which
    /// would shadow the `Display` impl and silently diverge from it.
    pub fn render(&self) -> String {
        let mut out = String::new();
        out.push_str("ISO-10303-21;\nHEADER;\n");
        for e in &self.header {
            e.write(&mut out, false);
        }
        out.push_str("ENDSEC;\nDATA;\n");
        for e in &self.data {
            e.write(&mut out, true);
        }
        out.push_str("ENDSEC;\nEND-ISO-10303-21;\n");
        out
    }
}

impl std::fmt::Display for StepFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.render())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE: &str = "\
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('a part'),'2;1');
FILE_NAME('box.step','2026-08-14T00:00:00',('me'),(''),'threers','','');
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
ENDSEC;
DATA;
#1=CARTESIAN_POINT('',(0.,0.,0.));
#2=DIRECTION('',(0.,0.,1.));
#3=AXIS2_PLACEMENT_3D('',#1,#2,$);
#4=PLANE('',#3);
ENDSEC;
END-ISO-10303-21;
";

    #[test]
    fn a_file_parses_into_its_two_sections() {
        let f = parse(SAMPLE).unwrap();
        assert_eq!(f.header.len(), 3);
        assert_eq!(f.data.len(), 4);
        assert_eq!(f.data[3].name, "PLANE");
        assert_eq!(f.data[3].args[1], Value::Ref(3));
        assert_eq!(f.data[2].args[3], Value::Omitted);
    }

    #[test]
    fn the_written_form_parses_back_the_same() {
        let a = parse(SAMPLE).unwrap();
        let b = parse(&a.to_string()).unwrap();
        assert_eq!(a.data, b.data);
        assert_eq!(a.header, b.header);
    }

    #[test]
    fn a_real_always_keeps_its_decimal_point() {
        // `{}` on 1.0f64 gives "1", which is an *integer* token in STEP and a
        // schema violation where a real is required.
        assert_eq!(real(1.0), "1.");
        assert_eq!(real(-0.5), "-0.5");
        assert_eq!(real(0.0), "0.");
        for x in [1.0, -2.5, 1e-7, 1e21, 6.02e23, f64::MIN_POSITIVE] {
            let s = real(x);
            assert!(s.contains('.'), "{x} wrote as `{s}`");
            let Value::Real(back) = parse_value(&s) else {
                panic!("`{s}` did not read back as a real");
            };
            assert_eq!(back, x, "{x} round-tripped as {back}");
        }
    }

    /// Parse a bare value, for the tests.
    fn parse_value(s: &str) -> Value {
        let mut p = Parser {
            s: s.as_bytes(),
            i: 0,
        };
        p.value().unwrap()
    }

    #[test]
    fn reals_are_accepted_in_every_spelling_that_occurs() {
        assert_eq!(parse_value("1."), Value::Real(1.0));
        assert_eq!(parse_value("1.E-3"), Value::Real(1e-3));
        assert_eq!(parse_value("-2.5E+2"), Value::Real(-250.0));
        assert_eq!(parse_value("+3"), Value::Int(3));
        // An integer where a real belongs is common and readable.
        assert_eq!(parse_value("7").as_real(), Some(7.0));
    }

    #[test]
    fn a_quote_inside_a_string_survives_the_round_trip() {
        let f = parse("DATA;#1=PERSON('O''Brien');ENDSEC;").unwrap();
        assert_eq!(f.data[0].args[0].as_text(), Some("O'Brien"));
        let again = parse(&f.to_string()).unwrap();
        assert_eq!(again.data[0].args[0].as_text(), Some("O'Brien"));
    }

    #[test]
    fn non_ascii_goes_through_the_utf16_directive() {
        let f = parse(r"DATA;#1=P('caf\X2\00E9\X0\ \X2\03A9\X0\');ENDSEC;").unwrap();
        assert_eq!(f.data[0].args[0].as_text(), Some("café Ω"));

        // And back out again, so a name survives a load/save cycle.
        let text = f.to_string();
        assert!(text.contains(r"\X2\00E9\X0\"), "{text}");
        assert_eq!(
            parse(&text).unwrap().data[0].args[0].as_text(),
            Some("café Ω")
        );
    }

    #[test]
    fn a_complex_instance_keeps_its_parts() {
        // How AP203 spells a rational B-spline surface: several entity names
        // juxtaposed, not comma-separated.
        let f = parse(
            "DATA;#1=(BOUNDED_SURFACE()B_SPLINE_SURFACE(3,3,((#2)),.UNSPECIFIED.,.F.,.F.,.F.)\
             RATIONAL_B_SPLINE_SURFACE(((1.,1.))));ENDSEC;",
        )
        .unwrap();
        let e = &f.data[0];
        assert!(e.name.is_empty());
        assert!(e.is("B_SPLINE_SURFACE"));
        assert!(e.is("RATIONAL_B_SPLINE_SURFACE"));
        assert!(!e.is("PLANE"));
        assert_eq!(e.part("B_SPLINE_SURFACE").unwrap()[0], Value::Int(3));
        assert_eq!(parse(&f.to_string()).unwrap().data, f.data);
    }

    #[test]
    fn comments_and_layout_do_not_change_the_result() {
        let terse = parse("DATA;#1=A(1,2);ENDSEC;").unwrap();
        let spaced = parse(
            "ISO-10303-21;\nDATA; /* a comment\n spanning lines */\n\
             #1 = A ( 1 , 2 ) ;\nENDSEC;\nEND-ISO-10303-21;",
        )
        .unwrap();
        assert_eq!(terse.data, spaced.data);
    }

    #[test]
    fn a_malformed_file_says_where_it_broke() {
        let e = parse("DATA;#1=A(1,;ENDSEC;").unwrap_err();
        assert!(e.at > 0, "{e}");
        assert!(e.to_string().contains("byte"), "{e}");
    }

    #[test]
    fn header_instances_are_numbered_so_they_can_be_referred_to() {
        // They carry no `#id` in the file, but are entities all the same.
        let f = parse(SAMPLE).unwrap();
        assert_eq!(f.header[0].name, "FILE_DESCRIPTION");
        assert_eq!(f.header[1].name, "FILE_NAME");
        assert!(f.header.iter().all(|h| h.id > 0));
        // ...and they come back out without ids.
        assert!(!f.to_string().contains("#1=FILE_DESCRIPTION"));
    }

    #[test]
    fn lookup_by_name_and_by_id() {
        let f = parse(SAMPLE).unwrap();
        assert_eq!(f.all("CARTESIAN_POINT").count(), 1);
        assert_eq!(f.index()[&4].name, "PLANE");
    }

    #[test]
    fn nested_lists_keep_their_shape() {
        let f = parse("DATA;#1=A(((1.,2.),(3.,4.)));ENDSEC;").unwrap();
        let outer = f.data[0].args[0].as_list().unwrap();
        assert_eq!(outer.len(), 2);
        assert_eq!(outer[1].as_list().unwrap()[0].as_real(), Some(3.0));
    }
}