flm_core/stdlib/features/numbering/many.rs
1//! Writing several counter values at once ([`format_many`]), such as
2//! `Eqs.~(1–3, 7, and 9)`, and the default number writer's algorithm for
3//! several values.
4//!
5//! The default [number writer](super::NumberWriter) groups the values by the
6//! counters they are numbered within, sorts each group and collapses its
7//! consecutive values into ranges (unless the counter style's
8//! [`ranges`](super::CounterStyleDecl::ranges) is off), and joins everything
9//! with the counter style's join texts. A counter style written by another
10//! writer goes through that writer instead, which may write the same values
11//! in any other way.
12
13use super::style::{
14 list_shape, number_pieces, on_worker, segments, CounterStyle, FormatError, FormatOptions,
15 Item, ListPiece, Mark, Piece, Segment,
16};
17use super::value::CounterValue;
18use super::writer::{JoinText, NumberOut, NumberedValue, WriteCx};
19
20/// One run: a sequence of consecutive values of one group, given by its first
21/// and its last value. A run of one value has the same value at both ends.
22#[derive(Clone, Copy)]
23struct Run<'a> {
24 first: NumberedValue<'a>,
25 last: NumberedValue<'a>,
26}
27
28/// Writes several counter values in `style` as one text and returns the
29/// segments of that text: the word, the delimiters, and the values as the
30/// counter style's [number writer](super::NumberWriter) writes them.
31///
32/// Each value carries the counters it is numbered within ([`NumberedValue`]),
33/// and the values come in the caller's order. Under the default writer:
34///
35/// - values numbered within the same counters, with the same values, and
36/// counted in the same scoped instance (or in none) form one group, and the
37/// groups are written in the order of their first value in the caller's
38/// list;
39/// - within a group, the values are sorted, and runs of consecutive values
40/// are collapsed into ranges; a range never spans two groups. A counter
41/// style whose [`ranges`](super::CounterStyleDecl::ranges) is off collapses
42/// nothing: the values are sorted and each is written separately, `1,2,3`;
43/// - a single run of exactly two consecutive values is written as two
44/// values, `1 and 2`, not as a range;
45/// - no value is removed: a value given twice is written twice.
46///
47/// The link marks of the segments are positions in the caller's list: the
48/// first value is `0`, regardless of where the sorting and the grouping put
49/// it. Each number links to its own value, and the texts that join numbers
50/// link to nothing. The word before the numbers links to the first number
51/// written when the counter style's
52/// [`name_in_link`](super::CounterStyleDecl::name_in_link) is on (the
53/// default), and to nothing otherwise; with a single value and `name_in_link`
54/// on, the whole text is one link.
55///
56/// With no value at all, the result is the counter style's `empty` join text,
57/// written without the word and without delimiters.
58///
59/// # Errors
60///
61/// The same as [`format`](super::format): a sub-number at a level the counter
62/// style declares no format for, a within-joiner that refers to a counter
63/// that is not an ancestor, and a failure to build the content.
64///
65/// # Examples
66///
67/// ```
68/// use flm_core::lang::{build_language, LangInputs};
69/// use flm_core::stdlib::features::numbering::{
70/// format_many, CounterStyleDecl, CounterValue, FormatOptions, JoinDecl, NumberedValue,
71/// };
72///
73/// let lang = build_language(LangInputs::new());
74/// let mut decl = CounterStyleDecl::new("example.style.item");
75/// decl.join = JoinDecl::compact();
76/// let style = decl.compile(&lang).expect("the style compiles");
77///
78/// let values = [CounterValue::new(3), CounterValue::new(1), CounterValue::new(2)];
79/// let written: Vec<NumberedValue<'_>> = values.iter().map(NumberedValue::new).collect();
80/// let segments = format_many(&style, &written, &FormatOptions::new())
81/// .expect("the numbers are written");
82/// // Three consecutive values are one range: `1`, `–`, `3`.
83/// assert_eq!(segments.len(), 3);
84/// assert_eq!(segments[0].link(), Some(1));
85/// assert_eq!(segments[1].link(), None);
86/// assert_eq!(segments[2].link(), Some(0));
87/// ```
88pub fn format_many(
89 style: &CounterStyle,
90 values: &[NumberedValue<'_>],
91 options: &FormatOptions,
92) -> Result<Vec<Segment>, FormatError> {
93 // The whole call runs on a worker thread, for the reason
94 // [`on_worker`](super::style::on_worker) gives.
95 on_worker(|| {
96 // A value's place among the caller's values is what its link mark
97 // carries, and it is the place in this list, whatever the writer then
98 // does with the values.
99 let numbered: Vec<NumberedValue<'_>> =
100 values.iter().enumerate().map(|(index, value)| value.at(index)).collect();
101 let cx = WriteCx::new(style);
102 let mut out = NumberOut::new();
103 style.writer().write_many(&numbered, options, &cx, &mut out)?;
104 segments(style, out.into_items())
105 })
106}
107
108/// Writes several values of one counter style as the default writer does.
109///
110/// [`WriteCx::default_many`] calls it, so a registered writer that hands a
111/// whole list to the default writer gets this result.
112///
113/// # Errors
114///
115/// The same as [`format_many`].
116pub(super) fn default_many<'a>(
117 values: &[NumberedValue<'a>],
118 options: &FormatOptions,
119 cx: &WriteCx<'a>,
120 out: &mut NumberOut<'a>,
121) -> Result<(), FormatError> {
122 let style = cx.style();
123 let count = values.len();
124 if count == 0 {
125 out.item(Item::text(cx.join_text(JoinText::Empty), Mark::Never));
126 return Ok(());
127 }
128 let groups = groups_of(values);
129 let runs = runs_of(&groups, style.ranges());
130 let mut items = join(cx, &runs)?;
131 let only_one = count == 1;
132
133 // The word takes the link of the first value there is one for; with one
134 // value the delimiters take it too, so that the whole text is one link.
135 let first = if style.name_in_link() {
136 items
137 .iter()
138 .find_map(|item| match item.mark {
139 Mark::Value(position) => Some(Mark::Value(position)),
140 _ => None,
141 })
142 .unwrap_or(Mark::Either)
143 } else {
144 Mark::Never
145 };
146 let around = if style.name_in_link() && only_one { Mark::Either } else { Mark::Never };
147
148 if options.with_word {
149 if let Some(word) = cx.word(count, options.variant.as_deref()) {
150 out.item(Item::text(word, first));
151 }
152 }
153 if options.with_delimiters {
154 out.item(Item::text(cx.open(), around));
155 }
156 out.items(items.drain(..));
157 if options.with_delimiters {
158 out.item(Item::text(cx.close(), around));
159 }
160 Ok(())
161}
162
163/// Returns the values grouped by the counters they are numbered within: two
164/// values are in one group when they were counted in the same scoped instance,
165/// or in none, and the same within-joiner writes before them the same
166/// ancestors, with the same values and of the same instances. A group keeps
167/// the place of its first value.
168///
169/// The groups decide which values may collapse into a range with each other:
170/// a range may only collapse numbers whose ancestors are written the same way,
171/// so `A.I` and `A.III` may, and `A.III` and `B.I` may not, even when the two
172/// counter values are consecutive.
173fn groups_of<'a>(values: &[NumberedValue<'a>]) -> Vec<Vec<NumberedValue<'a>>> {
174 let mut groups: Vec<Vec<NumberedValue<'a>>> = Vec::new();
175 for value in values {
176 match groups.iter().position(|group| same_parent(&group[0], value)) {
177 Some(index) => groups[index].push(*value),
178 None => groups.push(vec![*value]),
179 }
180 }
181 groups
182}
183
184/// Returns whether two values are numbered within the same counters, written
185/// by the same within-joiner: the same counters with the same values, in the
186/// same order, each counted in the same scoped instance, and the two values
187/// themselves counted in the same instance, since two instances are two
188/// separate sequences of the counter regardless of their ancestors.
189fn same_parent(left: &NumberedValue<'_>, right: &NumberedValue<'_>) -> bool {
190 if left.instance() != right.instance() {
191 return false;
192 }
193 let (left_parent, right_parent) = (left.parent(), right.parent());
194 match (left_parent, right_parent) {
195 (None, None) => true,
196 (Some(left_parent), Some(right_parent)) => {
197 // The joiners are compared by the address of their data alone,
198 // without the table of methods a trait object also carries, so two
199 // joiners that hold no data of their own compare equal. The values
200 // compared here come from the records of one counter table, where a
201 // counter holds its joiner beside the ancestors it is numbered
202 // within, so values with equal ancestors carry the one joiner
203 // anyway.
204 std::ptr::eq(
205 std::ptr::from_ref(left_parent.joiner).cast::<()>(),
206 std::ptr::from_ref(right_parent.joiner).cast::<()>(),
207 ) && left.ancestors().len() == right.ancestors().len()
208 && left.ancestors().iter().zip(right.ancestors()).all(|(one, other)| {
209 one.counter == other.counter
210 && one.value == other.value
211 && one.instance == other.instance
212 })
213 }
214 _ => false,
215 }
216}
217
218/// Returns the runs that the groups' values form: each group sorted,
219/// consecutive values collapsed into one run when `ranges` is on (each value a
220/// run of its own when it is off), the groups kept in order.
221///
222/// A result that is one run of exactly two values is split into two runs of
223/// one, so that a lone consecutive pair is written `1 and 2` instead of as a
224/// range.
225fn runs_of<'a>(groups: &[Vec<NumberedValue<'a>>], ranges: bool) -> Vec<Run<'a>> {
226 let mut runs: Vec<Run<'a>> = Vec::new();
227 for group in groups {
228 let mut entries: Vec<NumberedValue<'a>> = group.clone();
229 entries.sort_by(|left, right| left.value().cmp(right.value()));
230 let mut current: Option<Run<'a>> = None;
231 for entry in entries {
232 match current {
233 Some(run) if ranges && entry.value().immediately_succeeds(run.last.value()) => {
234 current = Some(Run { first: run.first, last: entry });
235 }
236 Some(run) => {
237 runs.push(run);
238 current = Some(Run { first: entry, last: entry });
239 }
240 None => current = Some(Run { first: entry, last: entry }),
241 }
242 }
243 if let Some(run) = current {
244 runs.push(run);
245 }
246 }
247 if runs.len() == 1 && runs[0].last.value().immediately_succeeds(runs[0].first.value()) {
248 let run = runs[0];
249 runs = vec![
250 Run { first: run.first, last: run.first },
251 Run { first: run.last, last: run.last },
252 ];
253 }
254 runs
255}
256
257/// Returns the items that the runs become, joined by the counter style's join
258/// texts: one run takes the `one_*` texts, two runs take the `pair_*` texts,
259/// more take the `list_*` texts, in the places [`list_shape`] gives.
260///
261/// The `one_pre` and `one_post` texts around a single run join the link of
262/// the run's value, if it has one; every other join text links to nothing.
263fn join<'a>(cx: &WriteCx<'a>, runs: &[Run<'a>]) -> Result<Vec<Item<'a>>, FormatError> {
264 // No run at all writes nothing: a call with no value answers the style's
265 // `empty` text before it gets here.
266 let mut items = Vec::new();
267 for piece in list_shape(runs.len()) {
268 match piece {
269 ListPiece::Text(which) => {
270 let mark = match which {
271 JoinText::OnePre | JoinText::OnePost => Mark::Either,
272 _ => Mark::Never,
273 };
274 items.push(Item::text(cx.join_text(which), mark));
275 }
276 ListPiece::Item(index) => items.append(&mut render(cx, &runs[index])?),
277 }
278 }
279 Ok(items)
280}
281
282/// Returns the items that one run becomes: its single value, or its two ends
283/// with the range texts around and between them.
284///
285/// The end of a range is written without the parts of its ancestors and
286/// without the leading components it shares with the start (`A.II.b–e`),
287/// unless the run is a pair of consecutive values or the counter style
288/// repeats the ancestors' parts.
289fn render<'a>(cx: &WriteCx<'a>, run: &Run<'a>) -> Result<Vec<Item<'a>>, FormatError> {
290 let style = cx.style();
291 if run.first.value() == run.last.value() {
292 let pieces = value_pieces(cx, &run.first, None)?;
293 return Ok(vec![Item { pieces, mark: Mark::Value(run.first.index()) }]);
294 }
295 let consecutive = run.last.value().immediately_succeeds(run.first.value());
296 let from = (!consecutive && !style.repeat_parents_in_range()).then(|| run.first.value());
297 let mid = if consecutive { JoinText::RangePairMid } else { JoinText::RangeMid };
298 Ok(vec![
299 Item::text(cx.join_text(JoinText::RangePre), Mark::Never),
300 Item {
301 pieces: value_pieces(cx, &run.first, None)?,
302 mark: Mark::Value(run.first.index()),
303 },
304 Item::text(cx.join_text(mid), Mark::Never),
305 Item {
306 pieces: value_pieces(cx, &run.last, from)?,
307 mark: Mark::Value(run.last.index()),
308 },
309 Item::text(cx.join_text(JoinText::RangePost), Mark::Never),
310 ])
311}
312
313/// Returns the pieces that one value becomes.
314///
315/// `from` is the start of the range that this value ends, when the value is
316/// written as the end of a range: the ancestors' parts are then left out, and
317/// so is every leading component the two values share.
318fn value_pieces<'a>(
319 cx: &WriteCx<'a>,
320 value: &NumberedValue<'a>,
321 from: Option<&CounterValue>,
322) -> Result<Vec<Piece<'a>>, FormatError> {
323 let own = value.value();
324 let mut number = Some(own.number());
325 let mut sub_numbers: Vec<Option<i64>> =
326 own.sub_numbers().iter().map(|sub| Some(*sub)).collect();
327 let mut within = Some((value, cx));
328 if let Some(from) = from {
329 within = None;
330 if from.number() == own.number() {
331 number = None;
332 }
333 for (level, sub_number) in sub_numbers.iter_mut().enumerate() {
334 if from.sub_numbers().get(level) == sub_number.as_ref() {
335 *sub_number = None;
336 }
337 }
338 }
339 let mut pieces = Vec::new();
340 number_pieces(cx.style(), number, &sub_numbers, within, &mut pieces)?;
341 Ok(pieces)
342}