techy 0.1.0

A fast, extensible LaTeX parser for Rust
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
//! The standard tables as a whole: the constructor that registers them
//! ([`SerdeSession::new`]) with its handle bundle ([`StandardTables`]), the extension
//! traits that intern into and read from them by kind ([`StandardTableInterning`],
//! [`StandardTableReading`]), and the drivers and positions of the spec and provider
//! tables ([`SpecSerdeDriver`], [`ProviderSerdeDriver`], [`SpecIndex`],
//! [`ProviderIndex`]).

use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;

use crate::scopes::SpecsProvider;
use crate::source::Source;
use crate::spec::CallableSpec;
use crate::state::ParsingState;

use super::super::engine::{
    DeserializeContext, DispatchingSerdeDriver, SerdeSession, SerializeContext, TableHandle,
};
use super::super::error::{DeserializeError, SerializeError};
use super::super::object::SerializableLang;
use super::diagnostic::DiagnosticSerdeDriver;
use super::parse_result::ParseResultSerdeDriver;
use super::source::{SourceIndex, SourceSerdeDriver};
use super::state::{StateIndex, StateSerdeDriver};
use super::tree::TreeSerdeDriver;
use super::{
    DIAGNOSTICS_TABLE, PARSE_RESULTS_TABLE, PROVIDERS_TABLE, SOURCES_TABLE, SPECS_TABLE, STATES_TABLE,
    TREES_TABLE,
};

crate::serial_index! {
    /// A position in the specs table — the `Index` type of [`SpecSerdeDriver`]: the
    /// serialized reference to a callable spec (`Arc<dyn CallableSpec<L>>`).
    pub struct SpecIndex;
}

crate::serial_index! {
    /// A position in the providers table — the `Index` type of
    /// [`ProviderSerdeDriver`]: the serialized reference to a specs provider
    /// (`Arc<dyn SpecsProvider<L>>`).
    pub struct ProviderIndex;
}

/// The driver of the specs table (table name `specs`): the [`DispatchingSerdeDriver`]
/// over `dyn CallableSpec<L>`.
///
/// Every spec type serializes itself through its own
/// [`SerializableObject::serialize_object`](crate::serialize::SerializableObject::serialize_object)
/// (a supertrait method of [`CallableSpec`]), and reading dispatches on the entry's
/// identifier through the readers and resolvers registered on the table's handle
/// ([`TableHandle::register_type`] and its siblings). Registered by
/// [`SerdeSession::new`].
pub type SpecSerdeDriver<L> = DispatchingSerdeDriver<L, dyn CallableSpec<L>, SpecIndex>;

/// The driver of the providers table (table name `providers`): the
/// [`DispatchingSerdeDriver`] over `dyn SpecsProvider<L>`.
///
/// Every provider type serializes itself through its own
/// [`SerializableObject::serialize_object`](crate::serialize::SerializableObject::serialize_object)
/// (a supertrait method of [`SpecsProvider`]), and reading dispatches on the entry's
/// identifier through the readers and resolvers registered on the table's handle
/// ([`TableHandle::register_type`] and its siblings). Registered by
/// [`SerdeSession::new`].
pub type ProviderSerdeDriver<L> = DispatchingSerdeDriver<L, dyn SpecsProvider<L>, ProviderIndex>;

/// The handles of a session's standard tables, by kind: what
/// [`SerdeSession::standard_tables`] returns for a session that has them (a session
/// built with [`SerdeSession::new`] always does).
#[non_exhaustive]
pub struct StandardTables<L: SerializableLang> {
    /// The sources table, named `sources` in the serialized form.
    pub sources: TableHandle<SourceSerdeDriver<L>>,
    /// The states table, named `states` in the serialized form.
    pub states: TableHandle<StateSerdeDriver<L>>,
    /// The specs table, named `specs` in the serialized form.
    pub specs: TableHandle<SpecSerdeDriver<L>>,
    /// The providers table, named `providers` in the serialized form.
    pub providers: TableHandle<ProviderSerdeDriver<L>>,
    /// The trees table, named `trees` in the serialized form.
    pub trees: TableHandle<TreeSerdeDriver<L>>,
    /// The diagnostics table, named `diagnostics` in the serialized form.
    pub diagnostics: TableHandle<DiagnosticSerdeDriver<L>>,
    /// The parse-results table, named `parse-results` in the serialized form.
    pub parse_results: TableHandle<ParseResultSerdeDriver<L>>,
}

impl<L: SerializableLang> Clone for StandardTables<L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: SerializableLang> Copy for StandardTables<L> {}

impl<L: SerializableLang> fmt::Debug for StandardTables<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StandardTables")
            .field("sources", &self.sources)
            .field("states", &self.states)
            .field("specs", &self.specs)
            .field("providers", &self.providers)
            .field("trees", &self.trees)
            .field("diagnostics", &self.diagnostics)
            .field("parse_results", &self.parse_results)
            .finish()
    }
}

impl<L: SerializableLang> SerdeSession<L> {
    /// Creates a session with the crate's standard tables registered.
    ///
    /// The tables, in registration order: sources ([`SourceSerdeDriver`], with its
    /// defaults — every source embedded, no supplier of referenced source text), states
    /// ([`StateSerdeDriver`]), specs ([`SpecSerdeDriver`]), providers
    /// ([`ProviderSerdeDriver`]), trees ([`TreeSerdeDriver`], with the unit annotation
    /// pre-registered), diagnostics ([`DiagnosticSerdeDriver`]), and parse results
    /// ([`ParseResultSerdeDriver`]).
    ///
    /// Their handles are [`standard_tables`](SerdeSession::standard_tables). Objects go
    /// in and come out either through those handles or through the by-kind extension
    /// traits: [`StandardTableInterning`] and [`StandardTableReading`] for sources,
    /// states, specs, and providers, and
    /// [`TreeSerialization`](crate::serialize::TreeSerialization),
    /// [`DiagnosticSerialization`](crate::serialize::DiagnosticSerialization), and
    /// [`ParseResultSerialization`](crate::serialize::ParseResultSerialization) for
    /// trees, diagnostics, and parse results.
    ///
    /// To configure the source driver, use
    /// [`with_source_driver`](SerdeSession::with_source_driver); to compose a session
    /// from other tables, [`empty`](SerdeSession::empty).
    ///
    /// The readers of the specs and providers tables, which are heterogeneous, are not
    /// registered here: writing needs none, and a reading session registers them once —
    /// the crate's own with
    /// [`register_core_readers`](crate::serialize::register_core_readers), a language's
    /// with its own helper (which calls the crate's — for the latexlike preset,
    /// [`latexlike::serialize::register`](crate::latexlike::serialize::register)), and a
    /// framework's own readers or its resolver on the handles
    /// ([`TableHandle::register_type`] and its siblings). The trees table has the unit
    /// annotation registered; other annotation types are registered with
    /// [`TableHandle::register_annotation`].
    pub fn new() -> SerdeSession<L> {
        SerdeSession::with_source_driver(SourceSerdeDriver::new())
    }

    /// [`new`](SerdeSession::new) with the given source driver in place of the default
    /// one.
    ///
    /// This is how the source text policy and supplier are configured (see
    /// [`SourceSerdeDriver::with_text_policy`] and
    /// [`SourceSerdeDriver::with_text_supplier`]).
    pub fn with_source_driver(sources: SourceSerdeDriver<L>) -> SerdeSession<L> {
        let mut session = SerdeSession::empty();
        // Invariant: an empty session accepts the seven standard tables — their names
        // are distinct, their homogeneous identifiers non-empty, and seven tables are
        // far below the table limit — so none of these registrations can fail.
        const ACCEPTED: &str = "an empty session accepts the standard tables";
        session.register_table(sources).expect(ACCEPTED);
        session.register_table(StateSerdeDriver::new()).expect(ACCEPTED);
        session.register_table(SpecSerdeDriver::<L>::new(SPECS_TABLE)).expect(ACCEPTED);
        session.register_table(ProviderSerdeDriver::<L>::new(PROVIDERS_TABLE)).expect(ACCEPTED);
        // The trees table registers the unit annotation itself.
        session.register_table(TreeSerdeDriver::<L>::new()).expect(ACCEPTED);
        session.register_table(DiagnosticSerdeDriver::<L>::new()).expect(ACCEPTED);
        session.register_table(ParseResultSerdeDriver::<L>::new()).expect(ACCEPTED);
        session
    }

    /// The handles of the standard tables, if this session has all of them (a session
    /// built with [`new`](SerdeSession::new) or
    /// [`with_source_driver`](SerdeSession::with_source_driver) always does; one
    /// built with [`empty`](SerdeSession::empty) has them when it registered them —
    /// found by name and driver type, see [`table_handle`](SerdeSession::table_handle)).
    pub fn standard_tables(&self) -> Option<StandardTables<L>> {
        Some(StandardTables {
            sources: self.table_handle(SOURCES_TABLE)?,
            states: self.table_handle(STATES_TABLE)?,
            specs: self.table_handle(SPECS_TABLE)?,
            providers: self.table_handle(PROVIDERS_TABLE)?,
            trees: self.table_handle(TREES_TABLE)?,
            diagnostics: self.table_handle(DIAGNOSTICS_TABLE)?,
            parse_results: self.table_handle(PARSE_RESULTS_TABLE)?,
        })
    }

    /// The name of the first standard table this session does not have, in the order
    /// [`standard_tables`](SerdeSession::standard_tables) looks them up — `None` when it
    /// has all seven.
    ///
    /// This is what a caller whose `standard_tables()` came back `None` names in its
    /// [`SerializeError::UnknownTableName`](crate::serialize::SerializeError::UnknownTableName)
    /// or its deserialization counterpart, so that the error names the table that is
    /// actually missing. A table registered under a standard name with another driver
    /// type counts as missing, as it does for `standard_tables`.
    pub(crate) fn missing_standard_table(&self) -> Option<&'static str> {
        if self.table_handle::<SourceSerdeDriver<L>>(SOURCES_TABLE).is_none() {
            Some(SOURCES_TABLE)
        } else if self.table_handle::<StateSerdeDriver<L>>(STATES_TABLE).is_none() {
            Some(STATES_TABLE)
        } else if self.table_handle::<SpecSerdeDriver<L>>(SPECS_TABLE).is_none() {
            Some(SPECS_TABLE)
        } else if self.table_handle::<ProviderSerdeDriver<L>>(PROVIDERS_TABLE).is_none() {
            Some(PROVIDERS_TABLE)
        } else if self.table_handle::<TreeSerdeDriver<L>>(TREES_TABLE).is_none() {
            Some(TREES_TABLE)
        } else if self.table_handle::<DiagnosticSerdeDriver<L>>(DIAGNOSTICS_TABLE).is_none() {
            Some(DIAGNOSTICS_TABLE)
        } else if self.table_handle::<ParseResultSerdeDriver<L>>(PARSE_RESULTS_TABLE).is_none() {
            Some(PARSE_RESULTS_TABLE)
        } else {
            None
        }
    }
}

impl<L: SerializableLang> Default for SerdeSession<L> {
    /// [`SerdeSession::new`]: the standard tables.
    fn default() -> Self {
        SerdeSession::new()
    }
}

/// Interning into the standard tables by kind: `intern_source`, `intern_state`,
/// `intern_spec`, and `intern_provider`.
///
/// The trait is implemented for [`SerdeSession`] and, so that a serialization call can
/// use the same methods, for [`SerializeContext`]. Each method finds the standard table
/// by name in the session and interns through it; the general operation is
/// [`SerdeSession::intern`] / [`SerializeContext::intern`] with a table handle.
///
/// An extension trait: bring it into scope with `use techy::serialize::StandardTableInterning;`.
pub trait StandardTableInterning<L: SerializableLang> {
    /// Intern `source` into the sources table (see [`SourceSerdeDriver`]), returning
    /// its position; a source already interned yields its existing position.
    ///
    /// # Errors
    ///
    /// The session has no sources table ([`SerializeError::UnknownTableName`]); the
    /// errors of [`SerdeSession::intern`].
    fn intern_source(&mut self, source: &Arc<Source<L::SourceOrigin>>) -> Result<SourceIndex, SerializeError>;

    /// Intern `state` into the states table (see [`StateSerdeDriver`]), returning its
    /// position; a state already interned yields its existing position.
    ///
    /// # Errors
    ///
    /// The session has no states table ([`SerializeError::UnknownTableName`]); the
    /// errors of [`SerdeSession::intern`].
    fn intern_state(&mut self, state: &Arc<ParsingState<L>>) -> Result<StateIndex, SerializeError>;

    /// Intern `spec` into the specs table (see [`SpecSerdeDriver`]), returning its
    /// position; a spec already interned yields its existing position.
    ///
    /// # Errors
    ///
    /// The session has no specs table ([`SerializeError::UnknownTableName`]); the
    /// spec does not participate in serialization ([`SerializeError::Unsupported`],
    /// wrapped in [`SerializeError::InTable`]); the errors of [`SerdeSession::intern`].
    fn intern_spec(&mut self, spec: &Arc<dyn CallableSpec<L>>) -> Result<SpecIndex, SerializeError>;

    /// Intern `provider` into the providers table (see [`ProviderSerdeDriver`]),
    /// returning its position; a provider already interned yields its existing
    /// position.
    ///
    /// # Errors
    ///
    /// The session has no providers table ([`SerializeError::UnknownTableName`]);
    /// the provider does not participate in serialization
    /// ([`SerializeError::Unsupported`], wrapped in [`SerializeError::InTable`]); the
    /// errors of [`SerdeSession::intern`].
    fn intern_provider(&mut self, provider: &Arc<dyn SpecsProvider<L>>) -> Result<ProviderIndex, SerializeError>;
}

/// Reading objects back from the standard tables by kind: `source`, `state`, `spec`,
/// and `provider`.
///
/// The trait is implemented for [`SerdeSession`] and, so that a deserialization call can
/// use the same methods, for [`DeserializeContext`]. Each method finds the standard
/// table by name in the session and reads through it; the general operation is
/// [`SerdeSession::object`] / [`DeserializeContext::object`] with a table handle. The
/// same position always yields the same `Arc`.
///
/// An extension trait: bring it into scope with `use techy::serialize::StandardTableReading;`.
pub trait StandardTableReading<L: SerializableLang> {
    /// The source at `position` of the sources table.
    ///
    /// # Errors
    ///
    /// The session has no sources table ([`DeserializeError::UnknownTableName`]);
    /// the errors of [`SerdeSession::object`].
    fn source(&mut self, position: SourceIndex) -> Result<Arc<Source<L::SourceOrigin>>, DeserializeError>;

    /// The state at `position` of the states table.
    ///
    /// # Errors
    ///
    /// The session has no states table ([`DeserializeError::UnknownTableName`]);
    /// the errors of [`SerdeSession::object`].
    fn state(&mut self, position: StateIndex) -> Result<Arc<ParsingState<L>>, DeserializeError>;

    /// The spec at `position` of the specs table.
    ///
    /// # Errors
    ///
    /// The session has no specs table ([`DeserializeError::UnknownTableName`]); the
    /// errors of [`SerdeSession::object`].
    fn spec(&mut self, position: SpecIndex) -> Result<Arc<dyn CallableSpec<L>>, DeserializeError>;

    /// The provider at `position` of the providers table.
    ///
    /// # Errors
    ///
    /// The session has no providers table ([`DeserializeError::UnknownTableName`]);
    /// the errors of [`SerdeSession::object`].
    fn provider(&mut self, position: ProviderIndex) -> Result<Arc<dyn SpecsProvider<L>>, DeserializeError>;
}

fn no_table_to_write(name: &str) -> SerializeError {
    SerializeError::UnknownTableName { name: String::from(name) }
}

fn no_table_to_read(name: &str) -> DeserializeError {
    DeserializeError::UnknownTableName { name: String::from(name) }
}

/// The two impls of [`StandardTableInterning`], for the session and the context —
/// which share the `table_handle` / `intern` surface.
macro_rules! standard_table_interning {
    ($($host:tt)*) => {
        impl<L: SerializableLang> StandardTableInterning<L> for $($host)* {
            fn intern_source(
                &mut self,
                source: &Arc<Source<L::SourceOrigin>>,
            ) -> Result<SourceIndex, SerializeError> {
                let table = self.table_handle::<SourceSerdeDriver<L>>(SOURCES_TABLE)
                    .ok_or_else(|| no_table_to_write(SOURCES_TABLE))?;
                self.intern(table, source)
            }

            fn intern_state(&mut self, state: &Arc<ParsingState<L>>) -> Result<StateIndex, SerializeError> {
                let table = self.table_handle::<StateSerdeDriver<L>>(STATES_TABLE)
                    .ok_or_else(|| no_table_to_write(STATES_TABLE))?;
                self.intern(table, state)
            }

            fn intern_spec(&mut self, spec: &Arc<dyn CallableSpec<L>>) -> Result<SpecIndex, SerializeError> {
                let table = self.table_handle::<SpecSerdeDriver<L>>(SPECS_TABLE)
                    .ok_or_else(|| no_table_to_write(SPECS_TABLE))?;
                self.intern(table, spec)
            }

            fn intern_provider(
                &mut self,
                provider: &Arc<dyn SpecsProvider<L>>,
            ) -> Result<ProviderIndex, SerializeError> {
                let table = self.table_handle::<ProviderSerdeDriver<L>>(PROVIDERS_TABLE)
                    .ok_or_else(|| no_table_to_write(PROVIDERS_TABLE))?;
                self.intern(table, provider)
            }
        }
    };
}

standard_table_interning!(SerdeSession<L>);
standard_table_interning!(SerializeContext<'_, L>);

/// The two impls of [`StandardTableReading`], for the session and the context —
/// which share the `table_handle` / `object` surface.
macro_rules! standard_table_reading {
    ($($host:tt)*) => {
        impl<L: SerializableLang> StandardTableReading<L> for $($host)* {
            fn source(
                &mut self,
                position: SourceIndex,
            ) -> Result<Arc<Source<L::SourceOrigin>>, DeserializeError> {
                let table = self.table_handle::<SourceSerdeDriver<L>>(SOURCES_TABLE)
                    .ok_or_else(|| no_table_to_read(SOURCES_TABLE))?;
                self.object(table, position)
            }

            fn state(&mut self, position: StateIndex) -> Result<Arc<ParsingState<L>>, DeserializeError> {
                let table = self.table_handle::<StateSerdeDriver<L>>(STATES_TABLE)
                    .ok_or_else(|| no_table_to_read(STATES_TABLE))?;
                self.object(table, position)
            }

            fn spec(&mut self, position: SpecIndex) -> Result<Arc<dyn CallableSpec<L>>, DeserializeError> {
                let table = self.table_handle::<SpecSerdeDriver<L>>(SPECS_TABLE)
                    .ok_or_else(|| no_table_to_read(SPECS_TABLE))?;
                self.object(table, position)
            }

            fn provider(
                &mut self,
                position: ProviderIndex,
            ) -> Result<Arc<dyn SpecsProvider<L>>, DeserializeError> {
                let table = self.table_handle::<ProviderSerdeDriver<L>>(PROVIDERS_TABLE)
                    .ok_or_else(|| no_table_to_read(PROVIDERS_TABLE))?;
                self.object(table, position)
            }
        }
    };
}

standard_table_reading!(SerdeSession<L>);
standard_table_reading!(DeserializeContext<'_, L>);