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
//! Tree-to-tree transformation: produce a new node tree from an existing one.
//!
//! A parsed [`NodeTree`](crate::core::node::NodeTree) is frozen, so an edit is
//! expressed as *restaging*: the driver reads the input tree and stages a copy of
//! each node into a fresh
//! [`NodeTreeBuilder`](crate::core::node::NodeTreeBuilder), applying the changes
//! the caller asked for along the way.
//!
//! The two items to know are a driver and a callback. You implement a
//! [`RestageVisitor`] — a closure is one — and pass it to the driver
//! [`TreeRestager`]: `TreeRestager::new(&mut visitor).restage(&tree)` calls the
//! visitor once per input node, starting at the root and working downward, and
//! returns the finished output tree. Between two visitor calls the driver stages
//! the nodes the callback asked for, translating each callable's argument and slot
//! records onto the new child layout; a node is staged only after all of its
//! children are, so a decision about a node is always taken before anything below
//! it exists in the output.
//!
//! This module is one of three tree consumers, which differ in what they produce:
//! [`visit`](crate::visit) produces nothing (a read-only traversal),
//! [`recompose`](crate::recompose) produces a single value such as a `String`, and
//! this one produces a new tree. [Node trees](crate::guide::node_trees) compares
//! the three on one page, and [Learn techy by
//! example](crate::guide::learn_by_example) works one transformation through from
//! parse to re-emitted source.
//!
//! ```
//! use techy::core::{Language, ParsingState};
//! use techy::core::node::{NodeId, NodeRef, NodeTree};
//! use techy::error::Recovery;
//! use techy::latexlike::{Latexlike, LatexlikeDriver};
//! use techy::transform::{Restage, RestageContext, RestageError, TreeRestager};
//!
//! // To record where an output node came from, the consumer's own annotation
//! // type stores the input node's id (ids are tagged with the tree that minted
//! // them, so an input id stays unambiguous inside an output annotation).
//! #[derive(Clone, Debug)]
//! struct Ann { original: NodeId }
//!
//! let language: Language<Latexlike> = Language::new(
//! LatexlikeDriver::new(Recovery::Strict),
//! ParsingState::lang_initial().expect("seed state"),
//! );
//! let input = language.parse("a{b}c").unwrap().tree;
//!
//! // Restage every node unchanged, annotating each copy with its original:
//! let output: NodeTree<Latexlike, Ann> = TreeRestager::new(
//! &mut |node: NodeRef<'_, Latexlike>,
//! _cx: &mut RestageContext<'_, Latexlike, (), Ann>| {
//! Ok::<_, core::convert::Infallible>(
//! Restage::Descend(Ann { original: node.id() }),
//! )
//! },
//! )
//! .restage(&input)
//! .unwrap();
//!
//! assert_eq!(output.root().annotation().original, input.root().id());
//! ```
//!
//! # What the visitor answers
//!
//! For each node the visitor returns a [`Restage`] value:
//!
//! - [`Descend(annotation)`](Restage::Descend) — the driver stages a copy of this
//! node over the results of its children, with the given annotation, and visits
//! every child subtree. There is no variant that keeps a node without visiting
//! its children: the only way a subtree goes unvisited is an explicit `Emit` for
//! one of its ancestors.
//! - [`Emit(nodes)`](Restage::Emit) — the callback has already staged the
//! replacement itself, through the [context](RestageContext)'s region operations
//! or its raw [`builder()`](RestageContext::builder); these are the staged nodes
//! that stand in for this node, and an empty vector drops it. The driver does not
//! descend afterwards, so a callback that still wants part of the subtree
//! restaged asks for it explicitly, for example with
//! [`restage_children`](RestageContext::restage_children).
//!
//! Descent is structural and never depends on the role a child plays in its
//! parent: the driver visits children in
//! [`Attached`](crate::core::node::SlotRole::Attached) and
//! [`Hidden`](crate::core::node::SlotRole::Hidden) slot regions exactly like any
//! other child. Copying attached content unchanged is one explicit arm of your
//! visitor, not something the driver does on its own.
//!
//! # The input is readable, the output is not
//!
//! A callback reads the frozen input node with the full node API and the
//! [`extract`](crate::extract) helpers, and produces staged output it can only
//! refer to by [`BuildId`] — a staged node cannot be read back. In particular a
//! `Descend` parent never sees its children's results, since the decision is taken
//! before they are staged; whatever a callback stages it produced itself, and any
//! fact it needs later goes into its own closure state or into an annotation.
//!
//! A pass that has to inspect transformed output finishes the tree and runs a
//! second pass over it. Chaining passes is cheap: annotations can be replaced
//! without copying the tree
//! ([`annotate`](crate::core::node::NodeTree::annotate)), and node payloads are
//! shared through `Arc`.
//!
//! # Annotations
//!
//! Every output node's annotation comes from the visitor — as the value in
//! `Descend(annotation)`, or as an explicit argument to the staging operation the
//! callback invokes. The input and output annotation types are separate type
//! parameters, so "keep the input annotation" is deliberately not expressible.
//!
//! To record where an output node came from, store the input node's id in your own
//! annotation type: `Descend(Ann { original: node.id(), .. })`, as in the example
//! above. To find the new node made for an old id, invert the finished tree's
//! annotations once, in time proportional to the number of nodes:
//!
//! ```text
//! let new_of_old: HashMap<NodeId, NodeId> = output
//! .iter_storage_order()
//! .map(|n| (n.annotation().original, n.id()))
//! .collect();
//! ```
//!
//! # Region edits are checked, never silently repaired
//!
//! The driver applies the same rules as construction during a parse: legal shapes
//! pass, and an edit that would leave a callable's records meaningless is an error.
//!
//! - Dropping every node of an argument's region restages the argument as
//! **provided with an empty region**. An absent argument means something
//! different from an empty one, and true absence is the explicit
//! [`RestagedArgument::absent`].
//! - Dropping the node that a record's
//! [`InChildrenOf`](crate::core::node::ContentNodes::InChildrenOf) content
//! designation points into — or replacing it with several nodes — is
//! [`RestageError::ContentParentDropped`]. Re-anchoring the designation
//! somewhere else would change what the record means, and for a multi-node
//! replacement there is no defined place to re-anchor it to. The remedy is to
//! take the callable over: `Emit` its replacement yourself, staged with
//! [`restage_invocation`](RestageContext::restage_invocation) or the raw builder.
//!
//! # Input nodes may come from any tree
//!
//! The context operations — and the
//! [`NodeTreeBuilder::restage_node`](crate::core::node::NodeTreeBuilder::restage_node)
//! primitive underneath them — accept nodes from **any** tree, not only from the
//! run's own input. This is supported by contract, so that one pass can assemble an
//! output tree out of pieces of several input trees.
use fmt;
use String;
use Vec;
use crate;
use crate;
use crateLang;
pub use ;
pub use ;
/// What a [`RestageVisitor`] asks the driver to do with one input node.
///
/// Returned from [`RestageVisitor::restage`]; the [module docs](self) describe how
/// the driver acts on each variant.
/// The callback half of a [`TreeRestager`] run: implement this, and the driver
/// calls it once per input node.
///
/// Each call receives a node of the frozen input tree and the
/// [`RestageContext`] to stage output through, and answers a [`Restage`] value;
/// the [module docs](self) describe the contract and what the driver does between
/// two calls.
///
/// Any `FnMut(NodeRef<'_, L, A>, &mut RestageContext<'_, L, A, B>) ->
/// Result<Restage<B>, E>` closure is a visitor through the blanket
/// implementation, which is all a pass that never re-enters itself needs. This is
/// a trait rather than a plain closure parameter because the context's region
/// operations re-enter the visitor from *inside* a visitor call —
/// `cx.restage_argument(node, 0, self)` — and a closure cannot pass itself.
///
/// An inline closure must annotate both of its parameter types: `&mut |node:
/// NodeRef<'_, L, A>, cx: &mut RestageContext<'_, L, A, B>| { … }`, as spelled in
/// the [module](self) example. A fully unannotated `|node, cx|` does not infer
/// against the generic visitor parameter, while a function item needs no
/// annotations at all.
///
/// A visitor need not be `Send` or `Sync` (nor need an
/// [`annotate`](crate::core::node::NodeTree::annotate) callback): the driver runs
/// visitors synchronously on the calling thread, so such a bound would constrain
/// callers without buying anything, and it would exclude single-threaded
/// foreign-function callbacks.
///
/// # Errors
///
/// `Error` is the visitor's own failure type. It is returned unchanged from
/// [`TreeRestager::restage`], as [`RestageError::Visitor`]. Context operations
/// fail with [`RestageError`]`<Self::Error>` values instead, so a visitor that
/// wants to propagate those with `?` gives its own error type a conversion:
///
/// ```text
/// enum PassError {
/// Restage(Box<RestageError<PassError>>), // context-op failures, boxed
/// BadReference(String), // the pass's own conditions
/// }
/// impl From<RestageError<PassError>> for PassError { … }
/// ```
/// Every suitable `FnMut` closure is a [`RestageVisitor`], which covers any pass
/// that does not re-enter itself.
/// The error that a [`TreeRestager`] run returns, where `E` is the error type of the
/// visitor.
///
/// An error of the visitor itself is returned unchanged as
/// [`Visitor`](RestageError::Visitor). The other variants report an error of the driver
/// or of a [`RestageContext`] operation: the output builder rejected the staged nodes
/// ([`Build`](RestageError::Build)), the visitor made a change that the driver cannot
/// apply to an argument or slot record
/// ([`ContentParentDropped`](RestageError::ContentParentDropped)), the input tree is
/// nested too deeply ([`DescentLimitExceeded`](RestageError::DescentLimitExceeded)), or
/// a [`RestageContext`] operation was called with invalid input. A call that violates
/// the documented requirements of an operation returns an error; it does not panic.
/// The run stops at the first error.
///
/// `Clone`, `PartialEq`, and `Eq` are implemented when `E` implements them.