Skip to main content

flm_core/lang/
ext.rs

1//! The data the FLM language attaches to parsing states and to nodes.
2//!
3//! techy lets a language attach data of its own to parsing states, to nodes,
4//! to arguments and to node slots (techy's `ParsedSlot`, the parts of a
5//! node's content outside its arguments, such as an environment's body).
6//! FLM attaches its own data to parsing states and to nodes (what arguments
7//! and slots carry is listed at
8//! [`FlmNodeExts`](crate::lang::flm::FlmNodeExts)):
9//!
10//! - The **state extension**, [`FlmStateExt`], is attached to every parsing
11//!   state. It holds what applies at the point where a node is built: the
12//!   [structural elements](crate::lang::structural), the restricted-interior
13//!   policy ([`RestrictedInterior`]) and the parsing settings of the file being
14//!   read ([`FlmParsing`]). A parsing state passes it on to the states derived
15//!   from it.
16//! - The **node extension**, [`FlmNodeExt`], is attached to every node. It is
17//!   built once, when techy adds the node to a tree, and never changes
18//!   afterwards. It holds the node's [element](crate::model::element::ElementSpec)
19//!   and two optional fields: where the characters of a rewritten text node come
20//!   from ([`TextSourceMap`]), and the typed payload of a presentation node, or
21//!   of a synthesized or rebuilt node that carries data of its own
22//!   ([`PresPayload`]).
23//!
24//! A [`TextSourceMap`] is a list of text source pieces ([`TextSourcePiece`]),
25//! each saying which source range a stretch of the node's text comes from; the
26//! pieces cover the text in order.
27//!
28//! A [`RestrictedInterior`] policy says what the interior of a restricted
29//! argument (a characters-only group or a verbatim region) still recognizes. In the parse of a document, it
30//! recognizes no command at all. In the parse of a [user
31//! definition](crate::lang::rewrites::userdefs::Definition)'s template, the
32//! policy keeps the command syntax of a placeholder enabled, so that a
33//! placeholder written inside a label, a reference target or raw text is still
34//! recognized. The policy lists tokenizer rules, so this module does not depend
35//! on how a placeholder is written.
36
37use std::any::Any;
38use std::fmt;
39use std::sync::{Arc, LazyLock};
40
41use techy::core::token::{
42    CommandOverrides, CommandRule, CommentOverrides, GroupOverrides, GroupRule,
43    SpecialsOverrides, TokenRulesOverrides,
44};
45use techy::core::constructs::verbatim_state_delta;
46use techy::core::{ParsingState, ParsingStateDelta};
47use techy::serialize::{DeserializableValue, SerialValue, SerializableValue};
48
49use crate::model::element::ElementSpec;
50use crate::lang::flm::{Flm, FlmGroupType};
51use crate::lang::origin::FlmSpan;
52use crate::lang::rules::FlmParsing;
53use crate::lang::structural::StructuralElements;
54
55// --- the presentation payload -------------------------------------------------------
56
57/// The trait every node payload type implements. A payload is the typed value
58/// a node holds beyond its element and its children; presentation nodes carry
59/// most payloads.
60///
61/// Lowering builds a presentation tree from a frozen document tree for one
62/// backend, and each presentation node carries a payload of the type its
63/// presentation element defines (a styled span's style, a block's role, a
64/// link's target). The backend that defines those presentation elements also
65/// defines the payload types. This trait is the only interface through which
66/// the [projection](crate::dump::project) (the serialized view of a tree that
67/// tests compare and that is printed for inspection) and the [serialization of
68/// a parse](crate::dump::session) read a payload, so that both can print and
69/// store it without knowing its concrete type.
70///
71/// Two other kinds of node may carry a payload:
72///
73/// - A node of a [synthesized element](crate::lang::mint::SyntaxDef::Synthesized)
74///   (an element no document writes, which a stage builds into a
75///   [synthesized value](crate::guide::concepts_overview#synthesized-values))
76///   may carry data that none of its arguments holds. For example, an
77///   [xnote](crate::stdlib::features::xnotes) is a note set apart from the
78///   running text and shown elsewhere or in place (a footnote, an endnote, a
79///   side note); the node that the list of xnotes holds for each xnote carries
80///   the address of that xnote. Such a payload may refer to a node of the document, which means
81///   something only in the run that built it. No reader is registered for it,
82///   so a tree holding one can be printed but not read back.
83/// - A node of the document that a rewrite pass rebuilt may carry a payload:
84///   each part of a cut [block-transparent
85///   element](crate::guide::concepts_overview#block-transparent-elements)
86///   carries the record its element attached, saying which cut it came from. Such a part is in the
87///   document tree itself, so a frozen tree holding it must read back from its
88///   serialized form like any other tree. The record is therefore plain data
89///   (which cut, which part, how many parts), and the feature that defines the
90///   element registers a reader for its payloads under the element's name in
91///   the reading session's [`PayloadReaders`](crate::dump::session::PayloadReaders)
92///   ([`reader_with`](crate::dump::session::reader_with)), as a backend does for
93///   its presentation elements.
94///
95/// A node's payload is held in [`FlmNodeExt::payload`].
96pub trait PresPayload: Any + Send + Sync + fmt::Debug {
97    /// Returns the payload as plain serialized data: what the
98    /// [projection](crate::dump::project) prints and what the
99    /// [serialization](crate::dump::session) writes.
100    ///
101    /// The reader registered for the node's element receives **exactly this
102    /// value** and must rebuild the payload from it alone
103    /// ([`PayloadReaders`](crate::dump::session::PayloadReaders)). The value
104    /// returned for a presentation node or a rebuilt node must therefore be
105    /// self-contained: no offset relative to the node's source, no node
106    /// identifier, nothing that only makes sense next to the tree it came from.
107    ///
108    /// The payload of a synthesized node is the exception, because no reader
109    /// rebuilds it (see the [trait documentation](PresPayload)): its value may
110    /// refer to the document node it shows, for a person reading the printed
111    /// tree, and it is never read back.
112    fn project(&self) -> SerialValue;
113}
114
115impl dyn PresPayload {
116    /// Returns whether this payload is a value of type `T`.
117    pub fn is<T: PresPayload>(&self) -> bool {
118        (self as &dyn Any).is::<T>()
119    }
120
121    /// Returns this payload as a `T`, or `None` when it is a payload of another
122    /// type.
123    pub fn downcast_ref<T: PresPayload>(&self) -> Option<&T> {
124        (self as &dyn Any).downcast_ref::<T>()
125    }
126}
127
128// --- the text source map ------------------------------------------------------------
129
130/// One text source piece of a [`TextSourceMap`]: the next
131/// [`out_len`](Self::out_len) bytes of the node's text come from the source
132/// bytes that [`span`](Self::span) covers.
133///
134/// Serialized form: `{len, span}`, the span in techy's own form, which records
135/// the source it belongs to.
136#[derive(Debug, Clone, PartialEq, Eq, SerializableValue, DeserializableValue)]
137#[serial(lang = Flm)]
138pub struct TextSourcePiece {
139    /// How many bytes of the node's text this piece covers.
140    #[serial(name = "len")]
141    pub out_len: u32,
142    /// The source bytes those text bytes come from. The span carries its own
143    /// source, so the pieces of one map may come from different sources.
144    #[serial(name = "span")]
145    pub span: FlmSpan,
146}
147
148/// Where each byte of a text node's text comes from, for a text node whose span
149/// alone does not say it.
150///
151/// Most text nodes are a byte-for-byte copy of one source range, and their span
152/// accounts for every byte; such nodes carry no map. The block-structure
153/// rewrite pass ([`crate::lang::rewrites::blocks`]) merges adjacent text nodes,
154/// collapses whitespace and applies typographic substitutions; a node whose
155/// text is then no longer a copy of one source range carries this map, in
156/// [`FlmNodeExt::source_map`].
157///
158/// The [text source pieces](Self::pieces) cover the node's text in order.
159/// Each maximal stretch of text that is a byte-for-byte copy of one source
160/// range is one piece, and a new piece starts wherever that stops being true:
161/// at a collapsed whitespace run, where two text nodes were merged, and at a
162/// substitution, even one that keeps the length (`---` becomes `—`, also three
163/// bytes).
164///
165/// Each piece carries its own span, and a span records its source, so one map
166/// may refer to several sources: text merged across the boundary of an
167/// expanded user definition does.
168///
169/// Serialized form: `{pieces: [...]}`.
170#[derive(Debug, Clone, PartialEq, Eq, Default, SerializableValue, DeserializableValue)]
171#[serial(lang = Flm)]
172pub struct TextSourceMap {
173    #[serial(name = "pieces")]
174    pieces: Vec<TextSourcePiece>,
175}
176
177impl TextSourceMap {
178    /// Returns a map over `pieces`, which must already be in text order.
179    pub fn new(pieces: Vec<TextSourcePiece>) -> TextSourceMap {
180        TextSourceMap { pieces }
181    }
182
183    /// Returns the text source pieces, in the order in which they cover the node's text.
184    pub fn pieces(&self) -> &[TextSourcePiece] {
185        &self.pieces
186    }
187
188    /// Returns how many bytes of the node's text the text source pieces cover,
189    /// in total.
190    ///
191    /// # Panics
192    ///
193    /// In debug builds, if the piece lengths sum to more than a `u32` holds. A
194    /// map is built from one node's text, so reaching that would take a text
195    /// node of more than four gigabytes.
196    pub fn total_len(&self) -> u32 {
197        self.pieces.iter().map(|piece| piece.out_len).sum()
198    }
199
200    /// Returns the text source piece covering the byte at `offset` in the
201    /// node's text, together with the byte's offset within that piece; `None`
202    /// for an offset at or past [`total_len`](Self::total_len).
203    ///
204    /// The piece's span says which source range that stretch of text comes
205    /// from. The byte at `offset` is not necessarily the byte at the same
206    /// distance into the span: a piece whose text was substituted or collapsed
207    /// covers a source range of a different length.
208    ///
209    /// # Panics
210    ///
211    /// In debug builds, under the same overflow condition as
212    /// [`total_len`](Self::total_len).
213    pub fn piece_at(&self, offset: u32) -> Option<(&TextSourcePiece, u32)> {
214        let mut start = 0u32;
215        for piece in &self.pieces {
216            let end = start + piece.out_len;
217            if offset < end {
218                return Some((piece, offset - start));
219            }
220            start = end;
221        }
222        None
223    }
224}
225
226// --- the node extension -----------------------------------------------------------
227
228/// The data FLM attaches to every node: its element, and two optional fields.
229///
230/// [`Flm::make_node_ext`](crate::techy::core::Lang::make_node_ext) builds it
231/// once, when techy adds the node to a tree. Every node has an
232/// [element](Self::element). A text node whose characters were rewritten also
233/// has a [source map](Self::source_map). A presentation node, and a synthesized
234/// or rebuilt node that carries data of its own, also has a
235/// [payload](Self::payload). A node copied into another tree keeps its
236/// extension unchanged; a node the library creates gets a new extension when it
237/// is created.
238#[derive(Clone)]
239pub struct FlmNodeExt {
240    /// The node's element: what the node means.
241    pub element: Arc<ElementSpec>,
242    /// Where each byte of a text node's text comes from; `None` means the text
243    /// is a byte-for-byte copy of the node's span.
244    pub source_map: Option<Arc<TextSourceMap>>,
245    /// The typed payload ([`PresPayload`]) of a presentation node, of a
246    /// synthesized node that carries data of its own, or of a node a rewrite
247    /// pass rebuilt with data of its own (a part of a cut [block-transparent
248    /// element](crate::guide::concepts_overview#block-transparent-elements),
249    /// carrying its cut
250    /// record); `None` on every other node.
251    pub payload: Option<Arc<dyn PresPayload>>,
252}
253
254impl FlmNodeExt {
255    /// Returns the extension of a node carrying `element`, with no source map
256    /// and no payload. A parse builds this for every node.
257    pub fn new(element: Arc<ElementSpec>) -> FlmNodeExt {
258        FlmNodeExt { element, source_map: None, payload: None }
259    }
260
261    /// Builder: sets `map` as the node's source map
262    /// ([`source_map`](Self::source_map)).
263    pub fn with_source_map(mut self, map: Arc<TextSourceMap>) -> FlmNodeExt {
264        self.source_map = Some(map);
265        self
266    }
267
268    /// Builder: sets `payload` as the node's payload
269    /// ([`payload`](Self::payload)).
270    pub fn with_payload(mut self, payload: Arc<dyn PresPayload>) -> FlmNodeExt {
271        self.payload = Some(payload);
272        self
273    }
274}
275
276impl fmt::Debug for FlmNodeExt {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        f.debug_struct("FlmNodeExt")
279            .field("element", &self.element.name)
280            .field("source_map", &self.source_map.as_ref().map(|map| map.pieces().len()))
281            .field("payload", &self.payload)
282            .finish()
283    }
284}
285
286// --- the state extension ------------------------------------------------------------
287
288/// One command syntax that stays recognized inside restricted arguments and
289/// verbatim regions during the parse of a template: an escape character, and
290/// the characters that may follow it to form a command name.
291///
292/// This is techy's [`CommandRule`] as plain data, so that a policy can be
293/// declared and serialized without holding a parser type.
294///
295/// Serialized form: `{escape_char, name_chars}`.
296#[derive(
297    Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize,
298    SerializableValue, DeserializableValue,
299)]
300pub struct TemplateCommandRule {
301    /// The escape character that starts the command.
302    #[serial(name = "escape_char")]
303    pub escape_char: char,
304    /// The characters that form a multi-character name after the escape
305    /// character; empty when only single-character names exist.
306    #[serial(name = "name_chars")]
307    pub name_chars: String,
308}
309
310/// The tokenizer rules that stay enabled inside a restricted argument or a
311/// verbatim region while the template of a [user
312/// definition](crate::lang::rewrites::userdefs::Definition) is parsed.
313///
314/// A user definition may pass one of its arguments into a label, a reference
315/// target or raw text, and the placeholder that marks where the argument goes
316/// must still be recognized there. The parse of a template therefore keeps the
317/// rules listed here enabled inside those regions; the template language keeps
318/// only the command syntax that starts a placeholder (`#`). Everything else is
319/// read as in a document.
320///
321/// Serialized form: `{commands: [...], specials}`.
322#[derive(
323    Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize,
324    SerializableValue, DeserializableValue,
325)]
326#[serde(default)]
327pub struct TemplateInteriorRules {
328    /// The command syntaxes that stay recognized; an empty list leaves commands
329    /// off.
330    #[serial(name = "commands")]
331    pub commands: Vec<TemplateCommandRule>,
332    /// Whether special character sequences are still recognized.
333    #[serial(name = "specials")]
334    pub specials: bool,
335}
336
337/// The restricted-interior policy: what the interior of a **restricted
338/// argument** recognizes. The parsing state carries it
339/// ([`FlmStateExt::restricted_interior`]).
340///
341/// The language has two restricted argument shapes, each read by a parser of
342/// its own: the characters-only group
343/// ([`FlmCharsGroupArgumentParser`](crate::lang::chars_group::FlmCharsGroupArgumentParser),
344/// as in `\label{…}` and `\ref{…}`) and the verbatim argument or environment
345/// body ([`crate::lang::verbatim`], as in `\verbcode{…}`). Both parsers read
346/// their interior under the parsing state this policy derives
347/// ([`chars_group_delta`](Self::chars_group_delta),
348/// [`verbatim_delta`](Self::verbatim_delta)), so one setting on the state
349/// decides for both whether a placeholder is recognized inside them. A
350/// [terminated argument](crate::lang::mint::ArgStdKind::Terminated) read as
351/// raw text is verbatim content too, and is read under the same policy
352/// ([`raw_text_delta`](Self::raw_text_delta)). The
353/// [module documentation of
354/// `lang::verbatim`](crate::lang::verbatim#the-two-restricted-argument-shapes)
355/// states how the two shapes differ.
356///
357/// Serialized form: `"document"`, or `{template: {commands, specials}}`.
358#[derive(
359    Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize,
360    SerializableValue, DeserializableValue,
361)]
362#[serde(rename_all = "kebab-case")]
363pub enum RestrictedInterior {
364    /// The policy of a document parse: no command and no special character
365    /// sequence is recognized inside a restricted argument, so `#` and `\` are
366    /// ordinary characters there.
367    #[default]
368    #[serial(name = "document")]
369    Document,
370    /// The policy of a template parse: the listed rules stay enabled inside a
371    /// restricted argument, so a placeholder written there is recognized.
372    #[serial(name = "template")]
373    Template(TemplateInteriorRules),
374}
375
376impl RestrictedInterior {
377    /// Returns the change of parsing state under which a verbatim region's
378    /// interior is read: techy's verbatim change ([`verbatim_state_delta`]:
379    /// every tokenizer rule off, with `terminator` as the only recognized
380    /// closing delimiter) and, under [`Template`](Self::Template), the listed
381    /// rules enabled again.
382    pub fn verbatim_delta(&self, terminator: Arc<GroupRule<Flm>>) -> ParsingStateDelta<Flm> {
383        let mut delta = verbatim_state_delta(terminator);
384        self.keep_template_rules(&mut delta.rules);
385        delta
386    }
387
388    /// Returns the change of parsing state under which raw text is read by a
389    /// parser that installs its terminator itself: the change of
390    /// [`verbatim_delta`](Self::verbatim_delta) (every tokenizer rule off,
391    /// and under [`Template`](Self::Template) the listed rules enabled
392    /// again), with the expected closing delimiter left as it is.
393    ///
394    /// A [terminated argument](crate::lang::mint::ArgStdKind::Terminated)
395    /// read as raw text uses it: the terminator of such an argument depends
396    /// on the run of characters that opens it at the use site, so the
397    /// terminator is known only once the parser has read that run, and the
398    /// parser then installs it as the expected closing delimiter of the
399    /// content.
400    pub fn raw_text_delta(&self) -> ParsingStateDelta<Flm> {
401        let mut rules = TokenRulesOverrides::disable_all();
402        self.keep_template_rules(&mut rules);
403        ParsingStateDelta::new().rules(rules)
404    }
405
406    /// Returns the change of parsing state under which a characters-only
407    /// group's interior is read. `base` is the state the argument itself is
408    /// parsed under, and `group_type` the group class of the argument's group.
409    ///
410    /// The change switches commands and special character sequences off and
411    /// comments on, and keeps only the group rules of `base` whose class is
412    /// `group_type`, so that the delimiters of mathematics, a different group
413    /// class, are read as characters. Under [`Template`](Self::Template), the
414    /// listed rules are enabled again on top of that.
415    pub fn chars_group_delta(
416        &self,
417        base: &ParsingState<Flm>,
418        group_type: FlmGroupType,
419    ) -> ParsingStateDelta<Flm> {
420        let mut rules = TokenRulesOverrides {
421            commands: CommandOverrides::disable(),
422            specials: SpecialsOverrides::disable(),
423            comments: CommentOverrides { enabled: Some(true), ..CommentOverrides::default() },
424            groups: GroupOverrides {
425                rules: Some(
426                    base.rules()
427                        .group_rules()
428                        .iter()
429                        .filter(|rule| rule.group_type == group_type)
430                        .cloned()
431                        .collect(),
432                ),
433                ..GroupOverrides::default()
434            },
435            ..TokenRulesOverrides::default()
436        };
437        self.keep_template_rules(&mut rules);
438        ParsingStateDelta::new().rules(rules)
439    }
440
441    /// Under [`Template`](Self::Template), turns the listed rules back on in
442    /// `rules`; under [`Document`](Self::Document), leaves `rules` as it is.
443    fn keep_template_rules(&self, rules: &mut TokenRulesOverrides<Flm>) {
444        let RestrictedInterior::Template(template) = self else {
445            return;
446        };
447        if !template.commands.is_empty() {
448            let commands = template
449                .commands
450                .iter()
451                .map(|rule| {
452                    Arc::new(CommandRule {
453                        escape_char: rule.escape_char,
454                        name_chars: rule.name_chars.clone(),
455                    })
456                })
457                .collect();
458            rules.commands = CommandOverrides { enabled: Some(true), rules: Some(commands) };
459        }
460        if template.specials {
461            rules.specials = SpecialsOverrides { enabled: Some(true) };
462        }
463    }
464
465    /// Returns whether this is the [`Template`](Self::Template) policy.
466    pub fn is_template(&self) -> bool {
467        matches!(self, RestrictedInterior::Template(_))
468    }
469}
470
471/// The shared default structural elements: the set a state carries until a
472/// built language installs the registry's own. techy requires a language's
473/// state extension to implement `Default`, and that default refers to this set.
474static DEFAULT_STRUCTURAL: LazyLock<Arc<StructuralElements>> =
475    LazyLock::new(|| Arc::new(StructuralElements::default()));
476
477/// The state extension: the data FLM attaches to every parsing state, which
478/// applies at the point where a node is built.
479///
480/// It holds the [structural elements](Self::structural), from which every node
481/// that is not a declared callable takes its element; the
482/// [restricted-interior policy](Self::restricted_interior); and the [parsing
483/// settings](Self::parsing) of the file being read.
484///
485/// The value never changes in place. A different extension is installed by
486/// deriving a new parsing state with it (`ParsingStateDelta::new().ext(…)`):
487/// [`crate::lang::build`] installs the registry's structural elements that way,
488/// and the parse of a template switches to the
489/// [`Template`](RestrictedInterior::Template) policy that way.
490#[derive(Debug, Clone)]
491pub struct FlmStateExt {
492    /// The structural elements that apply: the elements of the nodes that are
493    /// not declared callables.
494    pub structural: Arc<StructuralElements>,
495    /// What the interior of a restricted argument (a characters-only group or
496    /// a verbatim region) recognizes.
497    pub restricted_interior: RestrictedInterior,
498    /// The parsing settings under which the current file is read.
499    ///
500    /// In the document's primary file, these are the document's settings, which
501    /// the initial state of a built language carries. In a file included with
502    /// `\input`, they are the settings that apply where the command is written,
503    /// with the included file's own settings on top ([`crate::lang::input`]).
504    /// The language's initial parsing state, from which no document is parsed,
505    /// carries the defaults.
506    ///
507    /// The tokenizer rules of the state are derived from these settings; this
508    /// field records which settings they came from, for the code that needs
509    /// them during the parse: `\input` passes them to the embedding program
510    /// ([`InputResolver::resolve`](crate::lang::InputResolver::resolve)), and
511    /// the diagnostic for a lone `%`
512    /// ([`PercentForbidden`](crate::lang::PercentForbidden)) states from them how
513    /// to start a comment.
514    pub parsing: Arc<FlmParsing>,
515}
516
517impl FlmStateExt {
518    /// Returns an extension carrying `structural`, with the
519    /// [`Document`](RestrictedInterior::Document) restricted-interior policy and
520    /// the default parsing settings.
521    pub fn new(structural: Arc<StructuralElements>) -> FlmStateExt {
522        FlmStateExt {
523            structural,
524            restricted_interior: RestrictedInterior::Document,
525            parsing: Arc::new(FlmParsing::default()),
526        }
527    }
528
529    /// Builder: sets the parsing settings of the file being read
530    /// ([`parsing`](Self::parsing)). It only records them and changes no
531    /// tokenizer rule: the caller applies the matching rules
532    /// ([`FlmParsing::state_delta`] or [`FlmParsing::token_rules_overrides`]) in
533    /// the same derivation of the parsing state.
534    pub fn with_parsing(mut self, parsing: FlmParsing) -> FlmStateExt {
535        self.parsing = Arc::new(parsing);
536        self
537    }
538
539    /// Builder: sets the restricted-interior policy
540    /// ([`restricted_interior`](Self::restricted_interior)).
541    ///
542    /// # Examples
543    ///
544    /// ```
545    /// use flm_core::lang::{FlmStateExt, RestrictedInterior};
546    ///
547    /// let ext = FlmStateExt::default()
548    ///     .with_restricted_interior(RestrictedInterior::Template(Default::default()));
549    /// assert!(ext.restricted_interior.is_template());
550    /// ```
551    pub fn with_restricted_interior(mut self, policy: RestrictedInterior) -> FlmStateExt {
552        self.restricted_interior = policy;
553        self
554    }
555}
556
557impl Default for FlmStateExt {
558    fn default() -> FlmStateExt {
559        FlmStateExt::new(Arc::clone(&DEFAULT_STRUCTURAL))
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566    use techy::source::{Source, SourceSpan};
567
568    use crate::lang::origin::FlmSource;
569
570    #[test]
571    fn a_source_map_locates_the_piece_of_a_text_offset() {
572        let source: Arc<FlmSource> = Arc::new(Source::new("ab  cd"));
573        let map = TextSourceMap::new(vec![
574            TextSourcePiece { out_len: 2, span: SourceSpan::new(&source, 0..2) },
575            TextSourcePiece { out_len: 1, span: SourceSpan::new(&source, 2..4) },
576            TextSourcePiece { out_len: 2, span: SourceSpan::new(&source, 4..6) },
577        ]);
578        assert_eq!(map.total_len(), 5);
579        let (piece, within) = map.piece_at(3).unwrap();
580        assert_eq!(piece.span.range(), 4..6);
581        assert_eq!(within, 0);
582        assert!(map.piece_at(5).is_none());
583    }
584
585    #[test]
586    fn the_document_policy_is_the_default() {
587        assert_eq!(FlmStateExt::default().restricted_interior, RestrictedInterior::Document);
588        assert!(!RestrictedInterior::Document.is_template());
589    }
590}