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
//! Self-referential parser support through deferred construction.
//!
//! This module provides the [`Recursive`] wrapper that solves the circular
//! dependency problem when building parsers that need to reference themselves
//! directly or indirectly. Instead of constructing the parser immediately,
//! it defers construction using a closure and caches the result.
//!
//! Recursive parsers are essential for parsing nested structures like
//! arithmetic expressions, JSON objects, or any grammar with recursive
//! production rules.
use OnceCell;
use crate::;
/// A wrapper that enables self-referential parsers by deferring construction.
///
/// This solves the circular dependency problem where a parser needs to contain
/// itself (directly or indirectly). Instead of creating the parser during
/// construction, `Recursive<P>` creates it lazily on first use and caches it.
///
/// # The Problem
///
/// Self-referential parsers are common in language grammars but cause compilation issues:
///
/// ```compile_fail
/// // This won't compile - infinite type size!
/// struct Expression {
/// parenthesized: Expression, // ERROR: recursive without indirection
/// }
/// ```
///
/// # The Solution
///
/// `Recursive<P>` breaks the cycle during construction while enabling unlimited recursion at parse time:
///
/// ```rust
/// use std::io::Cursor;
/// use neotoma::{
/// recursive::Recursive,
/// parser::{Parser, Source, parse},
/// literal::Literal,
/// result::ParseResult,
/// cache::ParsingCache
/// };
///
/// // Example AST for expressions
/// #[derive(Debug, PartialEq, Clone)]
/// enum MyAst {
/// Atom(String),
/// Parenthesized(Box<MyAst>),
/// }
///
/// #[derive(Clone, Default)]
/// struct Expression {
/// // This compiles and works!
/// parenthesized: Recursive<Expression>,
/// }
///
/// impl Parser for Expression {
/// type Output = MyAst;
///
/// fn read<S>(
/// &self,
/// source: &mut Source<S>,
/// cache: &mut impl ParsingCache,
/// context: &mut ()
/// ) -> ParseResult<Self::Output>
/// where
/// S: neotoma::parser::Parsable,
/// {
/// // Try to parse parentheses like: (inner_expression)
/// let open_paren = Literal::from_str("(");
/// if open_paren.parse(source, cache, context).is_ok() {
/// // This creates unlimited recursion depth as needed
/// let inner = self.parenthesized.parse(source, cache, context)?;
/// let close_paren = Literal::from_str(")");
/// close_paren.parse(source, cache, context)?;
/// Ok(MyAst::Parenthesized(Box::new(inner)))
/// } else {
/// // Parse a simple atom (single letter)
/// let atom = Literal::from_str("x");
/// atom.parse(source, cache, context)?;
/// Ok(MyAst::Atom("x".to_string()))
/// }
/// }
/// }
///
/// // Test it works with nested parentheses
/// let parser = Expression::default();
/// let cursor = Cursor::new(b"((x))");
/// let mut source = Source::new(cursor);
///
/// let result = parse(parser, &mut source).unwrap();
/// assert_eq!(result, MyAst::Parenthesized(Box::new(
/// MyAst::Parenthesized(Box::new(MyAst::Atom("x".to_string())))
/// )));
/// ```
///
/// # How it works
///
/// 1. **Construction**: `Recursive::new()` creates an empty wrapper (no cycles)
/// 2. **First parse**: Creates the wrapped parser using `P::default()` and caches it
/// 3. **Subsequent parses**: Reuses the same cached instance for efficiency
///
/// This enables parsers that can handle arbitrarily deep nesting (like deeply nested parentheses)
/// without construction-time infinite recursion.
///
/// # Requirements
///
/// The wrapped parser type `P` must implement `Default` so that `Recursive<P>` can create
/// an instance when first needed.
// Implement Clone by creating a new empty Recursive
// (we don't want to share the cached instance between clones)