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
/// Advance byte offset to just after the next line break (handles \n and \r\n)
fn after_line_break(src: &[u8], mut off: usize) -> usize {
// Skip to newline if in middle of line
while off < src.len() && src[off] != b'\n' && src[off] != b'\r' {
off += 1;
}
if off < src.len() {
if src[off] == b'\r' {
off += 1;
if off < src.len() && src[off] == b'\n' {
off += 1;
}
} else if src[off] == b'\n' {
off += 1;
}
}
off
}
/// Unescape a string literal (e.g., convert \n to newline)
fn unescape_label(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
match next {
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'\\' => out.push('\\'),
'"' => out.push('"'),
'\'' => out.push('\''),
'$' => out.push('$'),
'@' => out.push('@'),
_ => {
out.push('\\');
out.push(next);
}
}
} else {
out.push('\\');
}
} else {
out.push(c);
}
}
out
}
/// Parse heredoc delimiter from a string like "<<EOF", "<<'EOF'", "<<~EOF", "<<`EOF`"
fn parse_heredoc_delimiter(s: &str) -> (String, bool, bool, bool) {
let mut chars = s.chars();
// Skip <<
chars.next();
chars.next();
// Check for indented heredoc
let indented = if chars.as_str().starts_with('~') {
chars.next();
true
} else {
false
};
let rest = chars.as_str().trim();
// Check for empty label (<<; or <<\n)
if rest.is_empty() || rest.starts_with(';') {
return (String::new(), true, indented, false);
}
// Check quoting to determine interpolation and command execution
let (delimiter, interpolated, command) =
if rest.starts_with('"') && rest.ends_with('"') && rest.len() >= 2 {
// Double-quoted: interpolated, unescape label
(unescape_label(&rest[1..rest.len() - 1]), true, false)
} else if rest.starts_with('\'') && rest.ends_with('\'') && rest.len() >= 2 {
// Single-quoted: not interpolated, no unescape
(rest[1..rest.len() - 1].to_string(), false, false)
} else if rest.starts_with('`') && rest.ends_with('`') && rest.len() >= 2 {
// Backtick: interpolated, command execution, unescape label
(unescape_label(&rest[1..rest.len() - 1]), true, true)
} else {
// Bare word: interpolated, no unescape (except maybe explicit escapes?)
// Bare identifiers don't usually have escapes, but can have weird chars?
// "EOF" -> EOF.
(rest.to_string(), true, false)
};
(delimiter, interpolated, indented, command)
}
/// Map heredoc delimiter text to collector QuoteKind
fn map_heredoc_quote_kind(text: &str, _interpolated: bool) -> heredoc_collector::QuoteKind {
// Skip << and optional ~
let rest = text.trim_start_matches('<').trim_start_matches('~').trim();
if rest.starts_with('\'') && rest.ends_with('\'') {
heredoc_collector::QuoteKind::Single
} else if rest.starts_with('"') && rest.ends_with('"') {
heredoc_collector::QuoteKind::Double
} else if rest.starts_with('`') && rest.ends_with('`') {
heredoc_collector::QuoteKind::Backtick
} else {
// Bare word (unquoted)
heredoc_collector::QuoteKind::Unquoted
}
}
const MAX_HEREDOC_DEPTH: usize = 100;
const HEREDOC_TIMEOUT_MS: u64 = 5000;
impl<'a> Parser<'a> {
/// Enqueue a heredoc declaration for later content collection
fn push_heredoc_decl(
&mut self,
label: String,
allow_indent: bool,
quote: heredoc_collector::QuoteKind,
decl_start: usize,
decl_end: usize,
) {
if self.pending_heredocs.len() >= MAX_HEREDOC_DEPTH {
self.errors.push(ParseError::syntax(
format!("Heredoc depth limit exceeded (max {})", MAX_HEREDOC_DEPTH),
decl_start,
));
return;
}
if self.pending_heredocs.is_empty() {
self.heredoc_start_time = Some(Instant::now());
}
self.pending_heredocs.push_back(PendingHeredoc {
label: Arc::from(label.as_str()),
allow_indent,
quote,
decl_span: heredoc_collector::Span { start: decl_start, end: decl_end },
});
}
/// Drain all pending heredocs after statement completion (FIFO order)
fn drain_pending_heredocs(&mut self, root: &mut Node) {
if self.pending_heredocs.is_empty() {
self.heredoc_start_time = None;
return;
}
// Check for timeout
if let Some(start) = self.heredoc_start_time {
if start.elapsed().as_millis() > HEREDOC_TIMEOUT_MS as u128 {
self.errors.push(ParseError::syntax(
format!("Heredoc parsing timed out (> {}ms)", HEREDOC_TIMEOUT_MS),
self.byte_cursor,
));
// Clear pending to prevent further processing/hanging
self.pending_heredocs.clear();
self.heredoc_start_time = None;
return;
}
}
// Advance to first content line (handle newline after statement terminator)
self.byte_cursor = after_line_break(self.src_bytes, self.byte_cursor);
// Keep a copy of the declarations so we can match outputs back to inputs
let pending: Vec<_> = self.pending_heredocs.iter().cloned().collect();
let out = collect_all(
self.src_bytes,
self.byte_cursor,
std::mem::take(&mut self.pending_heredocs),
);
// Zip 1:1 in order (collector preserves input order)
for (decl, body) in pending.into_iter().zip(out.contents.into_iter()) {
let mut attached = self.try_attach_heredoc_at_node(root, decl.decl_span, &body);
if !attached {
// Fallback: when statement recovery mutates span boundaries, the exact
// decl-span match may miss the placeholder node. In that case, attach to
// the next unresolved Heredoc node in source order.
attached = self.try_attach_next_unresolved_heredoc(root, &body);
}
if !body.terminated {
let label = if decl.label.is_empty() { "<empty>" } else { decl.label.as_ref() };
self.errors.push(ParseError::SyntaxError {
message: format!("Unterminated heredoc: {}", label),
location: self.src_bytes.len(),
});
}
// Defensive guardrail: warn if heredoc node wasn't found at expected span
#[cfg(debug_assertions)]
if !attached {
eprintln!(
"[WARNING] drain_pending_heredocs: Failed to attach heredoc content at span {}..{} - no matching Heredoc node found in AST",
decl.decl_span.start, decl.decl_span.end
);
}
}
self.byte_cursor = out.next_offset;
}
/// Attach collected heredoc content to its declaration node by matching declaration span
/// Returns true if a matching Heredoc node was found and updated, false otherwise
fn try_attach_heredoc_at_node(
&self,
root: &mut Node,
decl_span: heredoc_collector::Span,
body: &HeredocContent,
) -> bool {
// Depth-first search for the Heredoc node with matching declaration span
self.try_attach_at_node(root, decl_span, body)
}
/// Try to attach heredoc content at this node or its children
fn try_attach_at_node(
&self,
node: &mut Node,
decl_span: heredoc_collector::Span,
body: &HeredocContent,
) -> bool {
// Check if this node's span matches the declaration span
let node_matches =
node.location.start == decl_span.start && node.location.end == decl_span.end;
if node_matches {
// Try to attach at this node
if let NodeKind::Heredoc { content, body_span, .. } = &mut node.kind {
// Reify the body bytes from src_bytes using the collector's segments
let mut s = String::new();
for (i, seg) in body.segments.iter().enumerate() {
if seg.end > seg.start {
let bytes = &self.src_bytes[seg.start..seg.end];
// Source is valid UTF-8 (enforced by lexer)
s.push_str(std::str::from_utf8(bytes).unwrap_or_default());
}
if i + 1 < body.segments.len() {
// Normalize line breaks for AST convenience
s.push('\n');
}
}
*content = s;
// Store body span for breakpoint detection
*body_span = if body.full_span.start < body.full_span.end {
Some(SourceLocation {
start: body.full_span.start,
end: body.full_span.end,
})
} else {
None // Empty heredoc
};
return true;
}
}
// Recursively search children (DFS) using for_each_child_mut
let mut found = false;
node.for_each_child_mut(|child| {
if !found && self.try_attach_at_node(child, decl_span, body) {
found = true;
}
});
#[cfg(debug_assertions)]
if !found && node_matches {
eprintln!(
"warn: no Heredoc node found for decl span {}..{} (matched span but not Heredoc kind)",
decl_span.start, decl_span.end
);
}
found
}
/// Fallback attachment strategy used when exact declaration-span matching fails.
///
/// This can happen when error recovery shifts statement boundaries around the
/// heredoc declaration. The collector output still preserves FIFO order, so
/// attaching to the next unresolved Heredoc node keeps body/placeholder pairing
/// stable while avoiding dropped heredoc bodies.
fn try_attach_next_unresolved_heredoc(&self, root: &mut Node, body: &HeredocContent) -> bool {
self.try_attach_at_next_unresolved_node(root, body)
}
fn try_attach_at_next_unresolved_node(&self, node: &mut Node, body: &HeredocContent) -> bool {
if let NodeKind::Heredoc { content, body_span, .. } = &mut node.kind {
let unresolved = content.is_empty() && body_span.is_none();
if unresolved {
let mut text = String::new();
for (i, seg) in body.segments.iter().enumerate() {
if seg.end > seg.start {
let bytes = &self.src_bytes[seg.start..seg.end];
text.push_str(std::str::from_utf8(bytes).unwrap_or_default());
}
if i + 1 < body.segments.len() {
text.push('\n');
}
}
*content = text;
*body_span = if body.full_span.start < body.full_span.end {
Some(SourceLocation {
start: body.full_span.start,
end: body.full_span.end,
})
} else {
None
};
return true;
}
}
let mut found = false;
node.for_each_child_mut(|child| {
if !found && self.try_attach_at_next_unresolved_node(child, body) {
found = true;
}
});
found
}
}