Skip to main content

nomiscript/reader/
mod.rs

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
15mod atoms;
16mod forms;
17mod literals;
18mod strings;
19mod whitespace;
20
21#[cfg(test)]
22mod boolean_tests;
23#[cfg(test)]
24mod byte_vector_tests;
25#[cfg(test)]
26mod function_quote_tests;
27#[cfg(test)]
28mod number_tests;
29#[cfg(test)]
30mod tests;
31
32use anodized::spec;
33use tracing::debug;
34use winnow::combinator::alt;
35use winnow::error::{AddContext, ContextError, ErrMode, ModalResult, StrContext, StrContextValue};
36use winnow::prelude::*;
37
38use crate::ast::{Annotation, Expr, Program};
39use crate::error::{Error, Result};
40use crate::runtime::with_sufficient_stack;
41
42pub struct Reader;
43
44impl Reader {
45    pub fn parse(input: &str) -> Result<Program> {
46        debug!(input_len = input.len(), "parse start");
47        let mut remaining = input;
48        let (exprs, annotations) = parse_program(&mut remaining).map_err(|e| {
49            let offset = input.len() - remaining.len();
50            Error::parse(format_parse_error(e), input, offset..offset + 1)
51        })?;
52        debug!(
53            expr_count = exprs.len(),
54            annotation_count = annotations.len(),
55            "parse complete"
56        );
57        Ok(Program::with_annotations(exprs, annotations))
58    }
59
60    #[must_use]
61    pub fn is_incomplete(input: &str) -> bool {
62        let mut remaining = input;
63        parse_program(&mut remaining).is_err() && remaining.is_empty()
64    }
65
66    pub fn parse_expr(input: &str) -> Result<Expr> {
67        let mut remaining = input;
68        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    }
73}
74
75fn format_parse_error(err: ErrMode<ContextError>) -> String {
76    match err {
77        ErrMode::Backtrack(ctx) | ErrMode::Cut(ctx) => format_context_error(&ctx),
78        ErrMode::Incomplete(_) => "unexpected end of input".to_string(),
79    }
80}
81
82fn format_context_error(ctx: &ContextError) -> String {
83    if let Some(cause) = ctx.cause() {
84        return cause.to_string();
85    }
86    let mut parts = Vec::new();
87    for c in ctx.context() {
88        match c {
89            StrContext::Label(label) => parts.push(format!("in {label}")),
90            StrContext::Expected(StrContextValue::Description(desc)) => {
91                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    if parts.is_empty() {
103        "parse error".to_string()
104    } else {
105        parts.join(", ")
106    }
107}
108
109#[spec(ensures: |ref output| output.is_err() || input.is_empty())]
110fn parse_program(input: &mut &str) -> ModalResult<(Vec<Expr>, Vec<Annotation>)> {
111    let mut annotations = Vec::new();
112    whitespace::skip_ws_and_comments(input, &mut annotations)?;
113
114    let mut exprs = Vec::new();
115    loop {
116        if input.is_empty() {
117            break;
118        }
119        let expr = parse_expr(input)?;
120        exprs.push(expr);
121        whitespace::skip_ws_and_comments(input, &mut annotations)?;
122    }
123
124    Ok((exprs, annotations))
125}
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.
138pub const MAX_READ_DEPTH: usize = 64;
139
140thread_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.
145struct DepthGuard;
146
147impl Drop for DepthGuard {
148    fn drop(&mut self) {
149        READ_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
150    }
151}
152
153#[spec(
154    captures: [
155        depth_before = READ_DEPTH.with(std::cell::Cell::get),
156        len_before = input.len(),
157    ],
158    ensures: READ_DEPTH.with(std::cell::Cell::get) == depth_before,
159    ensures: |ref output| output.is_err() || input.len() < len_before,
160)]
161pub(super) fn parse_expr(input: &mut &str) -> ModalResult<Expr> {
162    let depth = READ_DEPTH.with(|d| {
163        let next = d.get() + 1;
164        d.set(next);
165        next
166    });
167    let _guard = DepthGuard;
168    if depth > MAX_READ_DEPTH {
169        return Err(ErrMode::Cut(
170            ContextError::new()
171                .add_context(input, &input.checkpoint(), StrContext::Label("expression"))
172                .add_context(
173                    input,
174                    &input.checkpoint(),
175                    StrContext::Expected(StrContextValue::Description(
176                        "nesting within the reader depth limit",
177                    )),
178                ),
179        ));
180    }
181
182    let expr = with_sufficient_stack(|| {
183        alt((
184            alt((
185                literals::parse_hash_literal,
186                forms::parse_function_quote,
187                literals::parse_number,
188                strings::parse_string,
189                forms::parse_quote,
190            )),
191            alt((
192                forms::parse_quasiquote,
193                forms::parse_unquote,
194                forms::parse_list,
195                atoms::parse_keyword,
196                atoms::parse_symbol,
197            )),
198        ))
199        .parse_next(input)
200    })?;
201    debug!(expr = ?expr, "parsed expression");
202    Ok(expr)
203}