stepq 0.2.0

Query, inspect, split and reshape STEP (ISO 10303-21) files — a library and a CLI, no geometry kernel required
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
//! Writer for the Part 21 exchange structure.
//!
//! Output is assembled from the source text. Every instance is copied
//! byte for byte from its original span — whitespace, comments, number
//! formatting and string escapes included — and only instance names
//! (`#id` tokens) are rewritten when renumbering. A string literal is a
//! single token, so `#` inside one is never touched. Comments inside an
//! instance are copied as they are, so a comment that mentions an old
//! `#id` keeps the old number.

use std::collections::BTreeMap;
use std::io::{BufWriter, Write};

use super::exchange::{Exchange, Instance};
use super::lexer::{Span, Token, TokenKind};
use crate::error::{Error, Result};

/// Text to write in place of individual tokens, such as a string literal
/// blanked or a name replaced. Every token without a replacement is still
/// copied from the source.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Replacements {
    /// By the token's start offset in the source: its end, and the text.
    by_start: BTreeMap<usize, (usize, Vec<u8>)>,
}

impl Replacements {
    /// No replacements.
    pub fn new() -> Self {
        Self::default()
    }

    /// Writes `text` instead of the token at `span`, which must be exactly
    /// one token's span, as from [`Literal::span`](super::Literal::span).
    /// `text` is written as given, so a string must include its quotes. A
    /// later replacement of the same token wins.
    pub fn replace(&mut self, span: Span, text: impl Into<Vec<u8>>) {
        self.by_start.insert(span.start, (span.end, text.into()));
    }

    /// The number of tokens replaced.
    pub fn len(&self) -> usize {
        self.by_start.len()
    }

    /// True if nothing is replaced.
    pub fn is_empty(&self) -> bool {
        self.by_start.is_empty()
    }

    fn get(&self, span: Span) -> Option<&[u8]> {
        self.by_start
            .get(&span.start)
            .filter(|(end, _)| *end == span.end)
            .map(|(_, text)| text.as_slice())
    }

    fn any_within(&self, span: Span) -> bool {
        self.by_start.range(span.start..span.end).next().is_some()
    }
}

/// How instance names are assigned in the output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Numbering {
    /// Keep every instance's original `#id`. Each written instance is then
    /// identical to its source text.
    #[default]
    Preserve,
    /// Number the written instances `#1`, `#2`, … in file order.
    Dense,
}

/// Writes all or part of an [`Exchange`] back out as Part 21.
///
/// ```
/// use stepq::p21::{Numbering, Writer, parse};
///
/// let src = b"ISO-10303-21;HEADER;FILE_SCHEMA(('X'));ENDSEC;DATA;\
///             #10=A(#30,'see #30');#20=B();#30=C();ENDSEC;END-ISO-10303-21;";
/// let exchange = parse(src)?;
/// let mut out = Vec::new();
/// // Write #10 and #30 only, renumbered.
/// Writer::new(&exchange)
///     .numbering(Numbering::Dense)
///     .write_selection([0, 2], &mut out)?;
/// let text = String::from_utf8(out).unwrap();
/// assert!(text.contains("DATA;\n#1=A(#2,'see #30');\n#2=C();\nENDSEC;\n"));
/// # Ok::<(), stepq::Error>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Writer<'e, 'a> {
    exchange: &'e Exchange<'a>,
    header: Option<&'e [u8]>,
    numbering: Numbering,
    replacements: Option<&'e Replacements>,
}

impl<'e, 'a> Writer<'e, 'a> {
    /// A writer for `exchange` that copies the source header and keeps
    /// instance names.
    pub fn new(exchange: &'e Exchange<'a>) -> Self {
        Self {
            exchange,
            header: None,
            numbering: Numbering::Preserve,
            replacements: None,
        }
    }

    /// Writes replacement text for individual tokens of the source header
    /// and of instances. Instances with no replaced token are still copied
    /// byte for byte; a header given with [`header`](Self::header) is
    /// written as given.
    #[must_use]
    pub fn replacements(self, replacements: &'e Replacements) -> Self {
        Self {
            replacements: Some(replacements),
            ..self
        }
    }

    /// Chooses how instance names are assigned.
    #[must_use]
    pub fn numbering(self, numbering: Numbering) -> Self {
        Self { numbering, ..self }
    }

    /// Replaces the header entities.
    ///
    /// `entities` is written between `HEADER;` and `ENDSEC;` exactly as
    /// given, so it must be complete header records, each ending in `;`.
    /// By default the source header is copied verbatim.
    #[must_use]
    pub fn header(self, entities: &'e [u8]) -> Self {
        Self {
            header: Some(entities),
            ..self
        }
    }

    /// Writes every instance.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnresolvedReference`] if the source itself has a
    /// dangling reference (nothing is written), and [`Error::Io`] if
    /// writing fails.
    pub fn write_all<W: Write>(&self, out: W) -> Result<()> {
        self.write_selection(0..self.exchange.instances().len(), out)
    }

    /// Writes the instances at `positions` — indices into
    /// [`Exchange::instances`] — once each and in file order, whatever
    /// order `positions` lists them in.
    ///
    /// Data sections are kept, with their parameters, even when none of
    /// their instances is selected.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnresolvedReference`] if a selected instance refers
    /// to one that is not selected. That is checked before anything is
    /// written: a file with a dangling reference is exactly the silent
    /// failure `docs/ARCHITECTURE.md` warns about. Returns [`Error::Io`] if
    /// writing fails.
    ///
    /// # Panics
    ///
    /// Panics if a position is out of range.
    pub fn write_selection<W: Write>(
        &self,
        positions: impl IntoIterator<Item = usize>,
        out: W,
    ) -> Result<()> {
        self.write_pruned(positions, [], out)
    }

    /// Like [`write_selection`](Self::write_selection), except that the
    /// instances at `pruned` positions may list instances that are not
    /// selected: those list items are removed, with their separating commas,
    /// and everything else in the instance is copied as usual.
    ///
    /// This is how an aggregate shared by many products — a layer
    /// assignment, a category — is written into a file holding only some of
    /// them. Only items of a list are removed; a pruned instance's other
    /// references must still be selected. A list can become empty, which the
    /// caller must avoid where the schema forbids it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnresolvedReference`] for a reference to an
    /// unselected instance that is not a list item of a pruned instance,
    /// before anything is written; [`Error::Io`] if writing fails.
    ///
    /// # Panics
    ///
    /// Panics if a position is out of range.
    pub fn write_pruned<W: Write>(
        &self,
        positions: impl IntoIterator<Item = usize>,
        pruned: impl IntoIterator<Item = usize>,
        out: W,
    ) -> Result<()> {
        let names = self.assign_names(positions);
        let mut is_pruned = vec![false; names.len()];
        for position in pruned {
            is_pruned[position] = true;
        }
        let plans = self.check_closed(&names, &is_pruned)?;
        let mut out = BufWriter::new(out);
        self.write_file(&mut out, &names, &plans)?;
        out.flush()?;
        Ok(())
    }

    /// The output name of every instance, by position; `None` if the
    /// instance is not selected.
    fn assign_names(&self, positions: impl IntoIterator<Item = usize>) -> Vec<Option<u64>> {
        let instances = self.exchange.instances();
        let mut names = vec![None; instances.len()];
        for position in positions {
            names[position] = Some(instances[position].id);
        }
        if self.numbering == Numbering::Dense {
            let mut next = 0;
            for name in names.iter_mut().flatten() {
                next += 1;
                *name = next;
            }
        }
        names
    }

    /// Checks that every selected instance's references resolve, and plans
    /// the list items to remove from pruned instances. Returns, by position,
    /// which of a pruned instance's tokens to drop.
    fn check_closed(
        &self,
        names: &[Option<u64>],
        pruned: &[bool],
    ) -> Result<Vec<Option<Vec<bool>>>> {
        let exchange = self.exchange;
        let mut plans = vec![None; names.len()];
        for (position, (instance, name)) in exchange.instances().iter().zip(names).enumerate() {
            if name.is_none() {
                continue;
            }
            if pruned[position] {
                plans[position] = Some(self.removal_plan(instance, names)?);
            } else {
                for id in exchange.references(instance) {
                    target_name(exchange, names, instance, id)?;
                }
            }
        }
        Ok(plans)
    }

    /// Which tokens of `instance` to drop so that no list item refers to an
    /// unselected instance, keeping exactly one comma between the items left.
    fn removal_plan(&self, instance: &Instance, names: &[Option<u64>]) -> Result<Vec<bool>> {
        let exchange = self.exchange;
        let tokens = exchange.instance_tokens(instance);

        // The `(` enclosing each token; a `(` right after a name opens a
        // record or typed value, not a list.
        let mut enclosing = vec![None; tokens.len()];
        let mut open = Vec::new();
        for (i, token) in tokens.iter().enumerate() {
            enclosing[i] = open.last().copied();
            match token.kind {
                TokenKind::LeftParen => open.push(i),
                TokenKind::RightParen => {
                    open.pop();
                }
                _ => {}
            }
        }
        let in_list = |i: usize| {
            enclosing[i].is_some_and(|paren: usize| {
                paren > 0
                    && !matches!(
                        tokens[paren - 1].kind,
                        TokenKind::Keyword | TokenKind::UserKeyword
                    )
            })
        };

        let mut removed = vec![false; tokens.len()];
        for (i, token) in tokens.iter().enumerate() {
            let TokenKind::InstanceName(id) = token.kind else {
                continue;
            };
            if target_name(exchange, names, instance, id).is_ok() {
                continue;
            }
            let before = i.checked_sub(1).map(|j| tokens[j].kind);
            let after = tokens.get(i + 1).map(|t| t.kind);
            let is_item = in_list(i)
                && matches!(before, Some(TokenKind::LeftParen | TokenKind::Comma))
                && matches!(after, Some(TokenKind::Comma | TokenKind::RightParen));
            if !is_item {
                return Err(Error::UnresolvedReference {
                    from: instance.id,
                    to: id,
                });
            }
            removed[i] = true;
            if after == Some(TokenKind::Comma) {
                removed[i + 1] = true;
            } else {
                // The last item: drop the nearest comma before it still kept.
                let mut j = i;
                while j > 0 {
                    j -= 1;
                    if removed[j] {
                        continue;
                    }
                    if tokens[j].kind == TokenKind::Comma {
                        removed[j] = true;
                    }
                    break;
                }
            }
        }
        Ok(removed)
    }

    fn write_file(
        &self,
        out: &mut impl Write,
        names: &[Option<u64>],
        plans: &[Option<Vec<bool>>],
    ) -> Result<()> {
        let exchange = self.exchange;
        out.write_all(b"ISO-10303-21;\nHEADER;")?;
        match (self.header, self.replacements) {
            (Some(header), _) => out.write_all(header)?,
            (None, Some(replacements)) if replacements.any_within(exchange.header_span()) => {
                write_replaced(
                    out,
                    exchange.source(),
                    exchange.header_span(),
                    exchange.header_tokens(),
                    replacements,
                )?;
            }
            (None, _) => out.write_all(exchange.header_text())?,
        }
        out.write_all(b"ENDSEC;\n")?;
        for (params, positions) in exchange.data_sections() {
            out.write_all(b"DATA")?;
            out.write_all(params)?;
            out.write_all(b";\n")?;
            for position in positions {
                if let Some(name) = names[position] {
                    self.write_instance(
                        out,
                        &exchange.instances()[position],
                        name,
                        names,
                        plans[position].as_deref(),
                    )?;
                    out.write_all(b"\n")?;
                }
            }
            out.write_all(b"ENDSEC;\n")?;
        }
        out.write_all(b"END-ISO-10303-21;\n")?;
        Ok(())
    }

    /// Writes one instance from its source text, renaming instance names
    /// when renumbering and dropping the tokens `removed` marks.
    fn write_instance(
        &self,
        out: &mut impl Write,
        instance: &Instance,
        name: u64,
        names: &[Option<u64>],
        removed: Option<&[bool]>,
    ) -> Result<()> {
        let exchange = self.exchange;
        let text = exchange.text(instance);
        let dense = self.numbering == Numbering::Dense;
        let replacements = self
            .replacements
            .filter(|replacements| replacements.any_within(instance.span));
        if !dense && removed.is_none() && replacements.is_none() {
            out.write_all(text)?;
            return Ok(());
        }

        let src = exchange.source();
        let mut cursor = instance.span.start;
        if dense {
            let digits = text
                .get(1..)
                .unwrap_or_default()
                .iter()
                .take_while(|b| b.is_ascii_digit())
                .count();
            write!(out, "#{name}")?;
            cursor += 1 + digits;
        }
        for (i, token) in exchange.instance_tokens(instance).iter().enumerate() {
            if removed.is_some_and(|removed| removed[i]) {
                out.write_all(&src[cursor..token.span.start])?;
                cursor = token.span.end;
            } else if let Some(text) = replacements.and_then(|r| r.get(token.span)) {
                out.write_all(&src[cursor..token.span.start])?;
                out.write_all(text)?;
                cursor = token.span.end;
            } else if let (true, TokenKind::InstanceName(id)) = (dense, token.kind) {
                let target = target_name(exchange, names, instance, id)?;
                out.write_all(&src[cursor..token.span.start])?;
                write!(out, "#{target}")?;
                cursor = token.span.end;
            }
        }
        out.write_all(&src[cursor..instance.span.end])?;
        Ok(())
    }
}

/// Writes `span` of `src`, with the replaced tokens among `tokens` swapped
/// for their replacement text.
fn write_replaced(
    out: &mut impl Write,
    src: &[u8],
    span: Span,
    tokens: &[Token],
    replacements: &Replacements,
) -> std::io::Result<()> {
    let mut cursor = span.start;
    for token in tokens {
        if token.span.start < cursor || token.span.end > span.end {
            continue;
        }
        if let Some(text) = replacements.get(token.span) {
            out.write_all(&src[cursor..token.span.start])?;
            out.write_all(text)?;
            cursor = token.span.end;
        }
    }
    out.write_all(&src[cursor..span.end])
}

/// The output name of the instance `from` refers to as `#id`.
fn target_name(
    exchange: &Exchange<'_>,
    names: &[Option<u64>],
    from: &Instance,
    id: u64,
) -> Result<u64> {
    exchange
        .position(id)
        .and_then(|position| names[position])
        .ok_or(Error::UnresolvedReference {
            from: from.id,
            to: id,
        })
}

#[cfg(test)]
mod tests {
    use std::io;

    use super::*;
    use crate::p21::parse;

    fn file_with(data: &str) -> String {
        format!(
            "ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('X'));\nENDSEC;\nDATA;\n{data}ENDSEC;\nEND-ISO-10303-21;\n"
        )
    }

    #[test]
    fn replacements_change_only_their_tokens() {
        let src = "ISO-10303-21;\nHEADER;\nFILE_NAME('a.stp','',('Jane'),('ACME'),'','','');\nFILE_SCHEMA(('X'));\nENDSEC;\nDATA;\n#10=A('secret',#20,'keep');\n#20=B('also secret');\n#30=C('untouched',  1.50);\nENDSEC;\nEND-ISO-10303-21;\n";
        let exchange = parse(src.as_bytes()).unwrap();
        let mut replacements = Replacements::new();
        let author = exchange
            .header_entity("FILE_NAME")
            .unwrap()
            .param(2)
            .unwrap();
        let author = author.list().unwrap().next().unwrap().literal().unwrap();
        replacements.replace(author.span(), "''");
        let records = |position: usize| {
            exchange
                .records(&exchange.instances()[position])
                .next()
                .unwrap()
        };
        let secret = records(0).param(0).unwrap().literal().unwrap();
        replacements.replace(secret.span(), "'x'");
        let also = records(1).param(0).unwrap().literal().unwrap();
        replacements.replace(also.span(), "''");
        assert_eq!(replacements.len(), 3);

        let mut out = Vec::new();
        Writer::new(&exchange)
            .replacements(&replacements)
            .write_all(&mut out)
            .unwrap();
        let text = String::from_utf8(out).unwrap();
        assert!(
            text.contains("FILE_NAME('a.stp','',(''),('ACME'),'','','');"),
            "{text}"
        );
        assert!(
            text.contains("#10=A('x',#20,'keep');\n#20=B('');\n#30=C('untouched',  1.50);\n"),
            "{text}"
        );

        let mut out = Vec::new();
        Writer::new(&exchange)
            .replacements(&replacements)
            .numbering(Numbering::Dense)
            .write_all(&mut out)
            .unwrap();
        let text = String::from_utf8(out).unwrap();
        assert!(
            text.contains("#1=A('x',#2,'keep');\n#2=B('');\n#3=C('untouched',  1.50);\n"),
            "{text}"
        );
    }

    fn write(src: &str, numbering: Numbering, positions: Option<&[usize]>) -> String {
        let exchange = parse(src.as_bytes()).unwrap();
        let writer = Writer::new(&exchange).numbering(numbering);
        let mut out = Vec::new();
        match positions {
            Some(positions) => writer.write_selection(positions.iter().copied(), &mut out),
            None => writer.write_all(&mut out),
        }
        .unwrap();
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn preserve_reproduces_the_source() {
        let src = file_with(
            "#1=A('x',#2);\n#2 = B ( /* keep */ 1.50E+01, '\\X2\\00E9\\X0\\' ) ;\n#3=(C()D(#1));\n",
        );
        assert_eq!(write(&src, Numbering::Preserve, None), src);
    }

    #[test]
    fn dense_renumbering_rewrites_only_instance_names() {
        let src = file_with(
            "#10=A(#30,'see #30');\n#20=B();\n#30=C(#10) /* was #10 */;\n#007=D((#20,#20));\n",
        );
        let expected =
            file_with("#1=A(#3,'see #30');\n#2=B();\n#3=C(#1) /* was #10 */;\n#4=D((#2,#2));\n");
        assert_eq!(write(&src, Numbering::Dense, None), expected);
    }

    #[test]
    fn selections_are_written_in_file_order() {
        let src = file_with("#10=A(#30,'see #30');\n#20=B();\n#30=C(#10);\n");
        assert_eq!(
            write(&src, Numbering::Dense, Some(&[2, 0, 2])),
            file_with("#1=A(#2,'see #30');\n#2=C(#1);\n")
        );
        assert_eq!(
            write(&src, Numbering::Preserve, Some(&[2, 0])),
            file_with("#10=A(#30,'see #30');\n#30=C(#10);\n")
        );
    }

    #[test]
    fn open_selections_are_rejected_before_writing() {
        let src = file_with("#10=A(#30);\n#20=B();\n#30=C();\n");
        let exchange = parse(src.as_bytes()).unwrap();
        let mut out = Vec::new();
        let err = Writer::new(&exchange)
            .write_selection([1, 0], &mut out)
            .unwrap_err();
        assert!(matches!(
            err,
            Error::UnresolvedReference { from: 10, to: 30 }
        ));
        assert!(out.is_empty());
    }

    #[test]
    fn header_can_be_replaced() {
        let src = file_with("#1=A();\n");
        let exchange = parse(src.as_bytes()).unwrap();
        let mut out = Vec::new();
        Writer::new(&exchange)
            .header(b"\nFILE_SCHEMA(('Y'));\n")
            .write_all(&mut out)
            .unwrap();
        assert_eq!(
            String::from_utf8(out).unwrap(),
            src.replace("('X')", "('Y')")
        );
    }

    #[test]
    fn sections_keep_their_parameters() {
        let src = "ISO-10303-21;HEADER;FILE_SCHEMA(('A','B'));ENDSEC;\
                   ANCHOR;<origin>=#1;ENDSEC;\
                   DATA ( 'one' , ('A') );#1=X();ENDSEC;\
                   DATA('two',('B'));#2=Y(#1);#3=Z();ENDSEC;\
                   END-ISO-10303-21;";
        assert_eq!(
            write(src, Numbering::Dense, Some(&[2])),
            "ISO-10303-21;\nHEADER;FILE_SCHEMA(('A','B'));ENDSEC;\n\
             DATA( 'one' , ('A') );\nENDSEC;\n\
             DATA('two',('B'));\n#1=Z();\nENDSEC;\n\
             END-ISO-10303-21;\n"
        );
    }

    #[test]
    fn io_errors_are_reported() {
        struct Full;
        impl Write for Full {
            fn write(&mut self, _: &[u8]) -> io::Result<usize> {
                Err(io::Error::other("disk full"))
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        let src = file_with("#1=A();\n");
        let exchange = parse(src.as_bytes()).unwrap();
        assert!(matches!(
            Writer::new(&exchange).write_all(Full),
            Err(Error::Io(_))
        ));
    }

    /// Positions 0–2 are #1–#3; 3–7 are the lists. #2 is left out.
    const LISTS: &str = "#1=A();\n#2=B();\n#3=C();\n\
         #10=L('middle',(#1, #2 ,#3));\n\
         #11=L('only',(#2));\n\
         #12=L('last and repeated',(#1,#2,#3,#2));\n\
         #13=L('nested',((#2,#1),#3));\n\
         #14=L('all',(#2,#2));\n";

    fn write_pruned(numbering: Numbering) -> String {
        let src = file_with(LISTS);
        let exchange = parse(src.as_bytes()).unwrap();
        let mut out = Vec::new();
        Writer::new(&exchange)
            .numbering(numbering)
            .write_pruned([0, 2, 3, 4, 5, 6, 7], [3, 4, 5, 6, 7], &mut out)
            .unwrap();
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn pruning_removes_list_items_and_their_commas() {
        assert_eq!(
            write_pruned(Numbering::Preserve),
            file_with(
                "#1=A();\n#3=C();\n\
                 #10=L('middle',(#1,  #3));\n\
                 #11=L('only',());\n\
                 #12=L('last and repeated',(#1,#3));\n\
                 #13=L('nested',((#1),#3));\n\
                 #14=L('all',());\n"
            )
        );
        assert_eq!(
            write_pruned(Numbering::Dense),
            file_with(
                "#1=A();\n#2=C();\n\
                 #3=L('middle',(#1,  #2));\n\
                 #4=L('only',());\n\
                 #5=L('last and repeated',(#1,#2));\n\
                 #6=L('nested',((#1),#2));\n\
                 #7=L('all',());\n"
            )
        );
    }

    #[test]
    fn pruning_never_removes_attributes_that_are_not_list_items() {
        for data in [
            "#1=A();\n#2=R(#1);\n",
            "#1=A();\n#2=R('x',#1);\n",
            "#1=A();\n#2=R(T(#1));\n",
            "#1=A();\n#2=(P(#1)Q());\n",
        ] {
            let src = file_with(data);
            let exchange = parse(src.as_bytes()).unwrap();
            let mut out = Vec::new();
            let err = Writer::new(&exchange)
                .write_pruned([1], [1], &mut out)
                .unwrap_err();
            assert!(
                matches!(err, Error::UnresolvedReference { from: 2, to: 1 }),
                "{data}"
            );
            assert!(out.is_empty(), "{data}");
        }
    }

    #[test]
    fn unpruned_instances_still_reject_open_selections() {
        let src = file_with(LISTS);
        let exchange = parse(src.as_bytes()).unwrap();
        let mut out = Vec::new();
        let err = Writer::new(&exchange)
            .write_pruned([0, 2, 3], [], &mut out)
            .unwrap_err();
        assert!(matches!(
            err,
            Error::UnresolvedReference { from: 10, to: 2 }
        ));
    }
}