1
//! S-expression reader (winnow-based).
2
//!
3
//! Public surface: [`Reader::parse`] for full programs and
4
//! [`Reader::parse_expr`] for a single expression. Internally split
5
//! into topic-focused submodules to stay under the ~500-line
6
//! CLAUDE.md guideline:
7
//! - [`whitespace`] — whitespace + `;` / `; @annotation` comments.
8
//! - [`literals`] — numbers (integer / decimal / rational), `#u8(...)` byte
9
//!   vectors, `#"..."` base64 bytes, and the `#t` / `#f` rejection.
10
//! - [`strings`] — `"..."` and `"""..."""` string literals.
11
//! - [`forms`] — `'`/`#'`/`,`/`,@`/`\`` reader macros and parenthesised
12
//!   lists (including dotted-pair tail).
13
//! - [`atoms`] — `:keyword` and bare symbols, including `nil` and `t`.
14

            
15
mod atoms;
16
mod forms;
17
mod literals;
18
mod strings;
19
mod whitespace;
20

            
21
#[cfg(test)]
22
mod boolean_tests;
23
#[cfg(test)]
24
mod byte_vector_tests;
25
#[cfg(test)]
26
mod function_quote_tests;
27
#[cfg(test)]
28
mod number_tests;
29
#[cfg(test)]
30
mod tests;
31

            
32
use anodized::spec;
33
use tracing::debug;
34
use winnow::combinator::alt;
35
use winnow::error::{AddContext, ContextError, ErrMode, ModalResult, StrContext, StrContextValue};
36
use winnow::prelude::*;
37

            
38
use crate::ast::{Annotation, Expr, Program};
39
use crate::error::{Error, Result};
40
use crate::runtime::with_sufficient_stack;
41

            
42
pub struct Reader;
43

            
44
impl Reader {
45
18062740
    pub fn parse(input: &str) -> Result<Program> {
46
18062740
        debug!(input_len = input.len(), "parse start");
47
18062740
        let mut remaining = input;
48
18062740
        let (exprs, annotations) = parse_program(&mut remaining).map_err(|e| {
49
13752
            let offset = input.len() - remaining.len();
50
13752
            Error::parse(format_parse_error(e), input, offset..offset + 1)
51
13752
        })?;
52
18048988
        debug!(
53
            expr_count = exprs.len(),
54
            annotation_count = annotations.len(),
55
            "parse complete"
56
        );
57
18048988
        Ok(Program::with_annotations(exprs, annotations))
58
18062740
    }
59

            
60
    #[must_use]
61
253136
    pub fn is_incomplete(input: &str) -> bool {
62
253136
        let mut remaining = input;
63
253136
        parse_program(&mut remaining).is_err() && remaining.is_empty()
64
253136
    }
65

            
66
592
    pub fn parse_expr(input: &str) -> Result<Expr> {
67
592
        let mut remaining = input;
68
592
        parse_expr(&mut remaining).map_err(|e| {
69
            let offset = input.len() - remaining.len();
70
            Error::parse(format_parse_error(e), input, offset..offset + 1)
71
        })
72
592
    }
73
}
74

            
75
13752
fn format_parse_error(err: ErrMode<ContextError>) -> String {
76
13752
    match err {
77
13752
        ErrMode::Backtrack(ctx) | ErrMode::Cut(ctx) => format_context_error(&ctx),
78
        ErrMode::Incomplete(_) => "unexpected end of input".to_string(),
79
    }
80
13752
}
81

            
82
13752
fn format_context_error(ctx: &ContextError) -> String {
83
13752
    if let Some(cause) = ctx.cause() {
84
630
        return cause.to_string();
85
13122
    }
86
13122
    let mut parts = Vec::new();
87
13122
    for c in ctx.context() {
88
24365
        match c {
89
11869
            StrContext::Label(label) => parts.push(format!("in {label}")),
90
            StrContext::Expected(StrContextValue::Description(desc)) => {
91
12496
                parts.push(format!("expected {desc}"));
92
            }
93
            StrContext::Expected(StrContextValue::CharLiteral(c)) => {
94
                parts.push(format!("expected '{c}'"));
95
            }
96
            StrContext::Expected(StrContextValue::StringLiteral(s)) => {
97
                parts.push(format!("expected \"{s}\""));
98
            }
99
            _ => {}
100
        }
101
    }
102
13122
    if parts.is_empty() {
103
208
        "parse error".to_string()
104
    } else {
105
12914
        parts.join(", ")
106
    }
107
13752
}
108

            
109
18315876
#[spec(ensures: |ref output| output.is_err() || input.is_empty())]
110
18315876
fn parse_program(input: &mut &str) -> ModalResult<(Vec<Expr>, Vec<Annotation>)> {
111
18315876
    let mut annotations = Vec::new();
112
18315876
    whitespace::skip_ws_and_comments(input, &mut annotations)?;
113

            
114
18315876
    let mut exprs = Vec::new();
115
    loop {
116
40832630
        if input.is_empty() {
117
18300044
            break;
118
22532586
        }
119
22532586
        let expr = parse_expr(input)?;
120
22516754
        exprs.push(expr);
121
22516754
        whitespace::skip_ws_and_comments(input, &mut annotations)?;
122
    }
123

            
124
18300044
    Ok((exprs, annotations))
125
18315876
}
126

            
127
/// Nesting the reader accepts before refusing the input.
128
///
129
/// `parse_expr` and `parse_list` are mutually recursive with a stack frame per
130
/// level, so without a ceiling a few kilobytes of `(((…` aborts the whole
131
/// process — and the reader is reachable from a report query parameter and from
132
/// the SSH eval channel. Same purpose as `MAX_SHARED_RECURSION_DEPTH`.
133
///
134
/// 64 is measured, not guessed: on a 2 MiB stack (the default for both tokio
135
/// workers and libtest threads) a debug build survives 128 levels and aborts at
136
/// 192, so this keeps a 2x margin — and is still far more nesting than any real
137
/// filter or program.
138
pub const MAX_READ_DEPTH: usize = 64;
139

            
140
thread_local! {
141
    static READ_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
142
}
143

            
144
/// Restores the reader's depth however the parser returns.
145
struct DepthGuard;
146

            
147
impl Drop for DepthGuard {
148
1107442427
    fn drop(&mut self) {
149
1107442427
        READ_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
150
1107442427
    }
151
}
152

            
153
#[spec(
154
    captures: [
155
1107442427
        depth_before = READ_DEPTH.with(std::cell::Cell::get),
156
1107442427
        len_before = input.len(),
157
    ],
158
1107442427
    ensures: READ_DEPTH.with(std::cell::Cell::get) == depth_before,
159
1107442427
    ensures: |ref output| output.is_err() || input.len() < len_before,
160
)]
161
1107442427
pub(super) fn parse_expr(input: &mut &str) -> ModalResult<Expr> {
162
1107442427
    let depth = READ_DEPTH.with(|d| {
163
1107442427
        let next = d.get() + 1;
164
1107442427
        d.set(next);
165
1107442427
        next
166
1107442427
    });
167
1107442427
    let _guard = DepthGuard;
168
1107442427
    if depth > MAX_READ_DEPTH {
169
832
        return Err(ErrMode::Cut(
170
832
            ContextError::new()
171
832
                .add_context(input, &input.checkpoint(), StrContext::Label("expression"))
172
832
                .add_context(
173
832
                    input,
174
832
                    &input.checkpoint(),
175
832
                    StrContext::Expected(StrContextValue::Description(
176
832
                        "nesting within the reader depth limit",
177
832
                    )),
178
832
                ),
179
832
        ));
180
1107441595
    }
181

            
182
1107441595
    let expr = with_sufficient_stack(|| {
183
1107441595
        alt((
184
1107441595
            alt((
185
1107441595
                literals::parse_hash_literal,
186
1107441595
                forms::parse_function_quote,
187
1107441595
                literals::parse_number,
188
1107441595
                strings::parse_string,
189
1107441595
                forms::parse_quote,
190
1107441595
            )),
191
1107441595
            alt((
192
1107441595
                forms::parse_quasiquote,
193
1107441595
                forms::parse_unquote,
194
1107441595
                forms::parse_list,
195
1107441595
                atoms::parse_keyword,
196
1107441595
                atoms::parse_symbol,
197
1107441595
            )),
198
1107441595
        ))
199
1107441595
        .parse_next(input)
200
1107441595
    })?;
201
1107368350
    debug!(expr = ?expr, "parsed expression");
202
1107368350
    Ok(expr)
203
1107442427
}