Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
sexpr.rs

1//! KiCad DSN-style S-expression parsing and deterministic building.
2//!
3//! The lexer borrows token text from the source and feeds the parser lazily.
4//! An owned tree is allocated only when [`parse`] is requested; future typed
5//! readers can consume [`Lexer`] directly without constructing this tree.
6
7use std::borrow::Cow;
8use std::fmt;
9use std::fmt::Write as _;
10
11mod lexer;
12
13/// The phase that produced an S-expression error.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum ErrorPhase {
16    /// UTF-8 validation or lexical scanning.
17    Lex,
18    /// Parenthesis or tree construction.
19    Tree,
20    /// Deterministic serialization.
21    Build,
22}
23
24/// Stable error classification for programmatic diagnostics.
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
26pub enum ErrorKind {
27    /// Input bytes were not valid UTF-8.
28    InvalidUtf8,
29    /// A quoted string did not terminate.
30    UnterminatedString,
31    /// No expression was present.
32    EmptyExpression,
33    /// The first token was not an opening parenthesis.
34    MissingOpeningParenthesis,
35    /// An opening parenthesis did not have a matching close.
36    UnbalancedOpeningParenthesis,
37    /// A closing parenthesis did not have a matching open.
38    UnbalancedClosingParenthesis,
39    /// Tokens remained after the root expression.
40    LeftoverGarbage,
41    /// A token did not satisfy a KiCad dialect production.
42    UnexpectedToken,
43    /// A numeric token exceeded the initial integer representation.
44    IntegerOutOfRange,
45    /// A configured parser resource limit was exceeded.
46    ResourceLimit,
47    /// A value could not be emitted safely.
48    InvalidBuildValue,
49    /// A source-preserving patch was invalid or overlapped another patch.
50    InvalidPatch,
51    /// Selector depth or path constraints were inconsistent.
52    InvalidSelector,
53    /// A form span did not belong to the supplied source.
54    InvalidSpan,
55    /// Native source reading or seeking failed.
56    Io,
57}
58
59/// One-based source line/column plus a zero-based byte offset.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct Position {
62    /// Zero-based byte offset.
63    pub offset: usize,
64    /// One-based line.
65    pub line: usize,
66    /// One-based Unicode-scalar column.
67    pub column: usize,
68}
69
70impl Position {
71    pub(crate) const START: Self = Self {
72        offset: 0,
73        line: 1,
74        column: 1,
75    };
76}
77
78/// Structured parse/build failure.
79#[derive(Clone, Debug, Eq, PartialEq)]
80pub struct Error {
81    /// Stage that raised the error.
82    pub phase: ErrorPhase,
83    /// Stable error category.
84    pub kind: ErrorKind,
85    /// Human-readable message compatible with the Python behavior family.
86    pub message: Cow<'static, str>,
87    /// Source position, when applicable.
88    pub position: Option<Position>,
89    /// Nearby token text, when useful.
90    pub token: Option<String>,
91}
92
93impl Error {
94    pub(crate) fn at(
95        phase: ErrorPhase,
96        kind: ErrorKind,
97        message: &'static str,
98        position: Position,
99    ) -> Self {
100        Self {
101            phase,
102            kind,
103            message: Cow::Borrowed(message),
104            position: Some(position),
105            token: None,
106        }
107    }
108
109    pub(crate) fn with_token(mut self, token: &str) -> Self {
110        self.token = Some(token.to_owned());
111        self
112    }
113
114    pub(crate) fn build(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Self {
115        Self {
116            phase: ErrorPhase::Build,
117            kind,
118            message: message.into(),
119            position: None,
120            token: None,
121        }
122    }
123}
124
125impl fmt::Display for Error {
126    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127        formatter.write_str(&self.message)?;
128        if let Some(position) = self.position {
129            write!(
130                formatter,
131                " at line {}, column {} (byte {})",
132                position.line, position.column, position.offset
133            )?;
134        }
135        if let Some(token) = &self.token {
136            write!(formatter, " near {token:?}")?;
137        }
138        Ok(())
139    }
140}
141
142impl std::error::Error for Error {}
143
144/// Owned compatibility tree produced on demand.
145#[derive(Clone, Debug)]
146pub enum Sexp {
147    /// Parenthesized child sequence.
148    List(Vec<Self>),
149    /// Unquoted atom.
150    Atom(String),
151    /// Quoted string after KiCad escape decoding.
152    Quoted(String),
153    /// Base-10 integer.
154    Integer(i64),
155    /// Decimal or exponent-form floating-point value.
156    Float(f64),
157}
158
159impl Drop for Sexp {
160    /// Drop a tree of any depth without recursion: KiCad files nest without a
161    /// depth ceiling, so the children are taken out onto a heap stack.
162    fn drop(&mut self) {
163        let Self::List(children) = self else {
164            return;
165        };
166        let mut pending = std::mem::take(children);
167        while let Some(mut node) = pending.pop() {
168            if let Self::List(grandchildren) = &mut node {
169                pending.append(grandchildren);
170            }
171        }
172    }
173}
174
175impl PartialEq for Sexp {
176    fn eq(&self, other: &Self) -> bool {
177        match (self, other) {
178            (Self::List(left), Self::List(right)) => left == right,
179            (Self::Atom(left), Self::Atom(right))
180            | (Self::Quoted(left), Self::Quoted(right))
181            | (Self::Atom(left), Self::Quoted(right))
182            | (Self::Quoted(left), Self::Atom(right)) => left == right,
183            (Self::Integer(left), Self::Integer(right)) => left == right,
184            (Self::Float(left), Self::Float(right)) => left == right,
185            (Self::Integer(integer), Self::Float(float))
186            | (Self::Float(float), Self::Integer(integer)) => (*integer as f64) == *float,
187            _ => false,
188        }
189    }
190}
191
192impl Sexp {
193    pub(crate) fn is_atom(&self, expected: &str) -> bool {
194        matches!(self, Self::Atom(value) if value == expected)
195    }
196}
197
198/// Borrowed lexical token category.
199#[derive(Clone, Copy, Debug, Eq, PartialEq)]
200pub enum TokenKind {
201    /// `(`.
202    Left,
203    /// `)`.
204    Right,
205    /// Bare non-numeric atom.
206    Atom,
207    /// Quoted string, including source quotes in [`Token::lexeme`].
208    QuotedString,
209    /// Integer lexical form.
210    Integer,
211    /// Decimal or exponent lexical form.
212    Float,
213}
214
215/// A token borrowing its exact text from the input.
216#[derive(Clone, Debug, Eq, PartialEq)]
217pub struct Token<'a> {
218    /// Token category.
219    pub kind: TokenKind,
220    /// Exact source bytes interpreted as UTF-8.
221    pub lexeme: &'a str,
222    /// Token start.
223    pub position: Position,
224}
225
226/// One source-preserving replacement over UTF-8 byte offsets.
227#[derive(Clone, Debug, Eq, PartialEq)]
228pub struct Patch<'a> {
229    /// Inclusive replacement start byte.
230    pub start_offset: usize,
231    /// Exclusive replacement end byte.
232    pub end_offset: usize,
233    /// Replacement text.
234    pub replacement: Cow<'a, str>,
235}
236
237/// Options for the generic token-preserving formatter.
238#[derive(Clone, Copy, Debug, Eq, PartialEq)]
239pub struct FormatOptions {
240    /// Spaces used for each displayed nesting level.
241    pub indentation_size: usize,
242    /// Lists deeper than this level remain inline.
243    pub max_nesting: usize,
244}
245
246impl Default for FormatOptions {
247    fn default() -> Self {
248        Self {
249            indentation_size: 2,
250            max_nesting: 2,
251        }
252    }
253}
254
255impl<'a> Patch<'a> {
256    /// Construct a patch borrowing or owning its replacement text.
257    pub fn new(
258        start_offset: usize,
259        end_offset: usize,
260        replacement: impl Into<Cow<'a, str>>,
261    ) -> Self {
262        Self {
263            start_offset,
264            end_offset,
265            replacement: replacement.into(),
266        }
267    }
268}
269
270/// Streaming lexer for the KiCad DSN-style dialect.
271#[derive(Clone, Debug)]
272pub struct Lexer<'a> {
273    source: &'a str,
274    position: Position,
275    line_start: usize,
276    finished: bool,
277}
278
279/// Collect borrowed tokens for diagnostics and compatibility tests.
280pub fn lex(source: &str) -> Result<Vec<Token<'_>>, Error> {
281    Lexer::new(source).collect()
282}
283
284/// Parse one UTF-8 KiCad S-expression.
285pub fn parse(source: &str) -> Result<Sexp, Error> {
286    Parser::new(source).parse()
287}
288
289/// Parse bytes after validating UTF-8.
290pub fn parse_bytes(source: &[u8]) -> Result<Sexp, Error> {
291    utf8_text(source).and_then(parse)
292}
293
294/// Validate bytes and borrow them as UTF-8 without constructing a syntax tree.
295pub fn utf8_text(source: &[u8]) -> Result<&str, Error> {
296    match std::str::from_utf8(source) {
297        Ok(text) => Ok(text),
298        Err(error) => {
299            let offset = error.valid_up_to();
300            let position = position_at_valid_prefix(&source[..offset]);
301            Err(Error::at(
302                ErrorPhase::Lex,
303                ErrorKind::InvalidUtf8,
304                "KiCad S-expression input is not valid UTF-8",
305                position,
306            ))
307        }
308    }
309}
310
311struct Parser<'a> {
312    lexer: Lexer<'a>,
313    lookahead: Option<Token<'a>>,
314}
315
316impl<'a> Parser<'a> {
317    fn new(source: &'a str) -> Self {
318        Self {
319            lexer: Lexer::new(source),
320            lookahead: None,
321        }
322    }
323
324    fn parse(mut self) -> Result<Sexp, Error> {
325        let Some(first) = self.peek_token()? else {
326            return Err(Error::at(
327                ErrorPhase::Tree,
328                ErrorKind::EmptyExpression,
329                "No or empty expression",
330                Position::START,
331            ));
332        };
333        if first.kind != TokenKind::Left {
334            return Err(Error::at(
335                ErrorPhase::Tree,
336                ErrorKind::MissingOpeningParenthesis,
337                "Missing initial opening parenthesis",
338                first.position,
339            )
340            .with_token(first.lexeme));
341        }
342
343        let result = self.parse_list()?;
344        if let Some(token) = self.peek_token()? {
345            if token.kind == TokenKind::Right {
346                return Err(Error::at(
347                    ErrorPhase::Tree,
348                    ErrorKind::UnbalancedClosingParenthesis,
349                    "Unbalanced closing parenthesis",
350                    token.position,
351                ));
352            }
353            return Err(Error::at(
354                ErrorPhase::Tree,
355                ErrorKind::LeftoverGarbage,
356                "Leftover garbage after end of expression",
357                token.position,
358            )
359            .with_token(token.lexeme));
360        }
361        Ok(result)
362    }
363
364    /// Parse one list of any nesting depth with an explicit stack, so deep
365    /// KiCad files cannot overflow the call stack. KiCad's own parser has no
366    /// depth ceiling.
367    fn parse_list(&mut self) -> Result<Sexp, Error> {
368        let open = self.expect(TokenKind::Left, "Expected opening parenthesis")?;
369        let mut stack = vec![(Vec::new(), open.position)];
370        loop {
371            let finished = match self.peek_kind()? {
372                Some(TokenKind::Right) => {
373                    self.take_token()?;
374                    true
375                }
376                Some(TokenKind::Left) => {
377                    let open = self.take_required("Expected opening parenthesis")?;
378                    stack.push((Vec::new(), open.position));
379                    false
380                }
381                Some(_) => {
382                    let token = self.take_required("Expected value token")?;
383                    let value = self.value_from_token(token)?;
384                    let (values, open_position) = stack.last_mut().expect("an open list");
385                    values.push(value);
386                    if values.len() == 1 && values[0].is_atom("teardrops") {
387                        let open_position = *open_position;
388                        self.parse_teardrops_body(values, open_position)?;
389                        true
390                    } else {
391                        false
392                    }
393                }
394                None => {
395                    let (_, open_position) = stack.last().expect("an open list");
396                    return Err(Error::at(
397                        ErrorPhase::Tree,
398                        ErrorKind::UnbalancedOpeningParenthesis,
399                        "Unbalanced opening parenthesis",
400                        *open_position,
401                    ));
402                }
403            };
404            if finished {
405                let (values, _) = stack.pop().expect("an open list");
406                let list = Sexp::List(values);
407                match stack.last_mut() {
408                    Some((parent, _)) => parent.push(list),
409                    None => return Ok(list),
410                }
411            }
412        }
413    }
414
415    fn parse_item(&mut self) -> Result<Sexp, Error> {
416        match self.peek_kind()? {
417            Some(TokenKind::Left) => self.parse_list(),
418            Some(TokenKind::Right) => {
419                let token = self.take_required("Expected closing parenthesis")?;
420                Err(Error::at(
421                    ErrorPhase::Tree,
422                    ErrorKind::UnbalancedClosingParenthesis,
423                    "Unbalanced closing parenthesis",
424                    token.position,
425                ))
426            }
427            Some(_) => {
428                let token = self.take_required("Expected value token")?;
429                self.value_from_token(token)
430            }
431            None => Err(Error::at(
432                ErrorPhase::Tree,
433                ErrorKind::UnbalancedOpeningParenthesis,
434                "Unbalanced opening parenthesis",
435                self.lexer.position(),
436            )),
437        }
438    }
439
440    #[allow(
441        clippy::cognitive_complexity,
442        reason = "pre-standard dialect parser retained under the structural ratchet"
443    )]
444    fn parse_teardrops_body(
445        &mut self,
446        values: &mut Vec<Sexp>,
447        open_position: Position,
448    ) -> Result<(), Error> {
449        loop {
450            match self.peek_kind()? {
451                Some(TokenKind::Right) => {
452                    self.take_token()?;
453                    return Ok(());
454                }
455                Some(TokenKind::Left) => {
456                    let list_open = self.take_required("Expected opening parenthesis")?;
457                    let Some(key_token) = self.take_token()? else {
458                        return Err(Error::at(
459                            ErrorPhase::Tree,
460                            ErrorKind::UnbalancedOpeningParenthesis,
461                            "Unexpected end of teardrops block",
462                            list_open.position,
463                        ));
464                    };
465                    if is_teardrop_field_key(&key_token) {
466                        values.push(self.parse_teardrop_field(key_token, true)?);
467                    } else {
468                        let first = self.value_from_token(key_token)?;
469                        values.push(self.parse_list_tail(vec![first], list_open.position)?);
470                    }
471                }
472                Some(TokenKind::Atom) => {
473                    let Some(key_token) = self.peek_token()? else {
474                        return Err(Error::at(
475                            ErrorPhase::Tree,
476                            ErrorKind::UnbalancedOpeningParenthesis,
477                            "Unbalanced opening parenthesis",
478                            open_position,
479                        ));
480                    };
481                    if !is_teardrop_field_key(&key_token) {
482                        return Err(Error::at(
483                            ErrorPhase::Tree,
484                            ErrorKind::UnexpectedToken,
485                            "Unexpected teardrops token",
486                            key_token.position,
487                        )
488                        .with_token(key_token.lexeme));
489                    }
490                    let key_token = self.take_required("Expected teardrops field")?;
491                    values.push(self.parse_teardrop_field(key_token, false)?);
492                }
493                Some(_) => {
494                    let Some(token) = self.peek_token()? else {
495                        return Err(Error::at(
496                            ErrorPhase::Tree,
497                            ErrorKind::UnbalancedOpeningParenthesis,
498                            "Unbalanced opening parenthesis",
499                            open_position,
500                        ));
501                    };
502                    return Err(Error::at(
503                        ErrorPhase::Tree,
504                        ErrorKind::UnexpectedToken,
505                        "Unexpected teardrops token",
506                        token.position,
507                    )
508                    .with_token(token.lexeme));
509                }
510                None => {
511                    return Err(Error::at(
512                        ErrorPhase::Tree,
513                        ErrorKind::UnbalancedOpeningParenthesis,
514                        "Unbalanced opening parenthesis",
515                        open_position,
516                    ));
517                }
518            }
519        }
520    }
521
522    fn parse_teardrop_field(
523        &mut self,
524        key_token: Token<'a>,
525        parenthesized: bool,
526    ) -> Result<Sexp, Error> {
527        let key = key_token.lexeme.to_owned();
528        let mut field = vec![Sexp::Atom(key.clone())];
529        if is_teardrop_bool_key(&key) {
530            if parenthesized {
531                if self.peek_kind()? == Some(TokenKind::Right) {
532                    self.take_token()?;
533                    return Ok(Sexp::List(field));
534                }
535                let Some(value_token) = self.take_token()? else {
536                    return Err(Error::at(
537                        ErrorPhase::Tree,
538                        ErrorKind::UnexpectedToken,
539                        "Expected yes/no for teardrops field",
540                        key_token.position,
541                    ));
542                };
543                if value_token.kind != TokenKind::Atom
544                    || !matches!(
545                        value_token.lexeme.to_ascii_lowercase().as_str(),
546                        "yes" | "no" | "true" | "false"
547                    )
548                {
549                    return Err(Error::at(
550                        ErrorPhase::Tree,
551                        ErrorKind::UnexpectedToken,
552                        "Expected yes/no for teardrops field",
553                        value_token.position,
554                    )
555                    .with_token(value_token.lexeme));
556                }
557                field.push(self.value_from_token(value_token)?);
558                self.expect(TokenKind::Right, "Expected closing parenthesis")?;
559            }
560            return Ok(Sexp::List(field));
561        }
562
563        if self.peek_kind()?.is_none() {
564            return Err(Error::at(
565                ErrorPhase::Tree,
566                ErrorKind::UnexpectedToken,
567                "Missing value for teardrops field",
568                key_token.position,
569            ));
570        }
571        field.push(self.parse_item()?);
572        self.expect(TokenKind::Right, "Expected closing parenthesis")?;
573        Ok(Sexp::List(field))
574    }
575
576    fn parse_list_tail(
577        &mut self,
578        mut values: Vec<Sexp>,
579        open_position: Position,
580    ) -> Result<Sexp, Error> {
581        loop {
582            match self.peek_kind()? {
583                Some(TokenKind::Right) => {
584                    self.take_token()?;
585                    return Ok(Sexp::List(values));
586                }
587                Some(_) => values.push(self.parse_item()?),
588                None => {
589                    return Err(Error::at(
590                        ErrorPhase::Tree,
591                        ErrorKind::UnbalancedOpeningParenthesis,
592                        "Unbalanced opening parenthesis",
593                        open_position,
594                    ));
595                }
596            }
597        }
598    }
599
600    fn value_from_token(&self, token: Token<'a>) -> Result<Sexp, Error> {
601        match token.kind {
602            TokenKind::Atom => Ok(Sexp::Atom(token.lexeme.to_owned())),
603            TokenKind::QuotedString => Ok(Sexp::Quoted(decode_quoted(token.lexeme))),
604            TokenKind::Integer => token.lexeme.parse::<i64>().map(Sexp::Integer).map_err(|_| {
605                Error::at(
606                    ErrorPhase::Tree,
607                    ErrorKind::IntegerOutOfRange,
608                    "Integer token is outside the initial i64 representation",
609                    token.position,
610                )
611                .with_token(token.lexeme)
612            }),
613            TokenKind::Float => token.lexeme.parse::<f64>().map(Sexp::Float).map_err(|_| {
614                Error::at(
615                    ErrorPhase::Tree,
616                    ErrorKind::UnexpectedToken,
617                    "Invalid floating-point token",
618                    token.position,
619                )
620                .with_token(token.lexeme)
621            }),
622            TokenKind::Left | TokenKind::Right => Err(Error::at(
623                ErrorPhase::Tree,
624                ErrorKind::UnexpectedToken,
625                "Expected value token",
626                token.position,
627            )),
628        }
629    }
630
631    fn peek_kind(&mut self) -> Result<Option<TokenKind>, Error> {
632        Ok(self.peek_token()?.map(|token| token.kind))
633    }
634
635    fn peek_token(&mut self) -> Result<Option<Token<'a>>, Error> {
636        self.fill_lookahead()?;
637        Ok(self.lookahead.clone())
638    }
639
640    fn take_token(&mut self) -> Result<Option<Token<'a>>, Error> {
641        self.fill_lookahead()?;
642        Ok(self.lookahead.take())
643    }
644
645    fn take_required(&mut self, message: &'static str) -> Result<Token<'a>, Error> {
646        let position = self.lexer.position();
647        self.take_token()?.ok_or_else(|| {
648            Error::at(
649                ErrorPhase::Tree,
650                ErrorKind::UnbalancedOpeningParenthesis,
651                message,
652                position,
653            )
654        })
655    }
656
657    fn fill_lookahead(&mut self) -> Result<(), Error> {
658        if self.lookahead.is_some() {
659            return Ok(());
660        }
661        self.lookahead = match self.lexer.next() {
662            Some(result) => Some(result?),
663            None => None,
664        };
665        Ok(())
666    }
667
668    fn expect(&mut self, expected: TokenKind, message: &'static str) -> Result<Token<'a>, Error> {
669        let Some(token) = self.take_token()? else {
670            return Err(Error::at(
671                ErrorPhase::Tree,
672                ErrorKind::UnbalancedOpeningParenthesis,
673                message,
674                self.lexer.position(),
675            ));
676        };
677        if token.kind != expected {
678            return Err(Error::at(
679                ErrorPhase::Tree,
680                ErrorKind::UnexpectedToken,
681                message,
682                token.position,
683            )
684            .with_token(token.lexeme));
685        }
686        Ok(token)
687    }
688}
689
690/// Deterministically build a KiCad S-expression from an owned tree.
691pub fn build(value: &Sexp) -> Result<String, Error> {
692    build_with_limit(value, usize::MAX)
693}
694
695/// Deterministically build while refusing to allocate beyond an output limit.
696pub fn build_with_limit(value: &Sexp, max_output_bytes: usize) -> Result<String, Error> {
697    let mut output = BuildOutput::new(max_output_bytes);
698    build_into(value, "", &mut output)?;
699    Ok(output.text)
700}
701
702/// Reformat source tokens without materializing an owned expression tree.
703///
704/// Token spelling is retained exactly. Whitespace and whole-line comments are
705/// intentionally normalized, matching the Python foundation formatter.
706pub fn format(source: &str, options: FormatOptions) -> Result<String, Error> {
707    let mut output = String::with_capacity(source.len().saturating_add(1));
708    let mut depth = 0_usize;
709    let mut last_kind = None;
710
711    for token in Lexer::new(source) {
712        let token = token?;
713        match token.kind {
714            TokenKind::Left => {
715                if !output.is_empty() {
716                    if depth <= options.max_nesting {
717                        trim_one_trailing_space(&mut output);
718                        output.push('\n');
719                        push_spaces(&mut output, options.indentation_size.saturating_mul(depth));
720                    } else if last_kind == Some(TokenKind::Right) {
721                        output.push(' ');
722                    }
723                }
724                depth = depth.saturating_add(1);
725                output.push('(');
726            }
727            TokenKind::Right => {
728                trim_one_trailing_space(&mut output);
729                depth = depth.checked_sub(1).ok_or_else(|| {
730                    Error::at(
731                        ErrorPhase::Tree,
732                        ErrorKind::UnbalancedClosingParenthesis,
733                        "Unbalanced closing parenthesis",
734                        token.position,
735                    )
736                })?;
737                if depth < options.max_nesting {
738                    output.push('\n');
739                    push_spaces(&mut output, options.indentation_size.saturating_mul(depth));
740                } else if last_kind == Some(TokenKind::Right) {
741                    output.push(' ');
742                }
743                output.push(')');
744            }
745            _ => {
746                if last_kind == Some(TokenKind::Right) {
747                    output.push(' ');
748                }
749                output.push_str(token.lexeme);
750                output.push(' ');
751            }
752        }
753        last_kind = Some(token.kind);
754    }
755
756    if depth != 0 {
757        return Err(Error::at(
758            ErrorPhase::Tree,
759            ErrorKind::UnbalancedOpeningParenthesis,
760            "Unbalanced opening parenthesis",
761            Position::START,
762        ));
763    }
764    output.push('\n');
765    Ok(output)
766}
767
768fn trim_one_trailing_space(output: &mut String) {
769    if output.ends_with(' ') {
770        output.pop();
771    }
772}
773
774fn push_spaces(output: &mut String, count: usize) {
775    output.extend(std::iter::repeat_n(' ', count));
776}
777
778/// Apply sorted, non-overlapping source patches.
779pub fn apply_patches(source: &str, patches: &[Patch<'_>]) -> Result<String, Error> {
780    apply_patches_with_limit(source, patches, usize::MAX)
781}
782
783/// Apply sorted, non-overlapping patches while bounding result bytes.
784pub fn apply_patches_with_limit(
785    source: &str,
786    patches: &[Patch<'_>],
787    max_output_bytes: usize,
788) -> Result<String, Error> {
789    let mut last_end = 0;
790    let mut output_size = source.len();
791
792    for patch in patches {
793        let valid_range = patch.start_offset <= patch.end_offset
794            && patch.end_offset <= source.len()
795            && source.is_char_boundary(patch.start_offset)
796            && source.is_char_boundary(patch.end_offset);
797        if !valid_range || patch.start_offset < last_end {
798            let bounded_offset = patch.start_offset.min(source.len());
799            return Err(Error {
800                phase: ErrorPhase::Build,
801                kind: ErrorKind::InvalidPatch,
802                message: Cow::Borrowed(
803                    "Patches must be sorted, non-overlapping, in-range UTF-8 byte ranges",
804                ),
805                position: Some(position_at_text_offset(source, bounded_offset)),
806                token: None,
807            });
808        }
809
810        let removed = patch.end_offset - patch.start_offset;
811        output_size = output_size
812            .checked_sub(removed)
813            .and_then(|size| size.checked_add(patch.replacement.len()))
814            .ok_or_else(|| {
815                Error::build(
816                    ErrorKind::ResourceLimit,
817                    "Patched S-expression output size overflowed",
818                )
819            })?;
820        if output_size > max_output_bytes {
821            return Err(Error::build(
822                ErrorKind::ResourceLimit,
823                "Patched S-expression output exceeds max_output_bytes",
824            ));
825        }
826        last_end = patch.end_offset;
827    }
828
829    let mut output = String::with_capacity(output_size);
830    last_end = 0;
831    for patch in patches {
832        output.push_str(&source[last_end..patch.start_offset]);
833        output.push_str(&patch.replacement);
834        last_end = patch.end_offset;
835    }
836    output.push_str(&source[last_end..]);
837    Ok(output)
838}
839
840struct BuildOutput {
841    text: String,
842    max_bytes: usize,
843}
844
845impl BuildOutput {
846    fn new(max_bytes: usize) -> Self {
847        Self {
848            text: String::new(),
849            max_bytes,
850        }
851    }
852
853    fn push(&mut self, character: char) -> Result<(), Error> {
854        let required = character.len_utf8();
855        self.reserve(required)?;
856        self.text.push(character);
857        Ok(())
858    }
859
860    fn push_str(&mut self, value: &str) -> Result<(), Error> {
861        self.reserve(value.len())?;
862        self.text.push_str(value);
863        Ok(())
864    }
865
866    fn reserve(&self, additional: usize) -> Result<(), Error> {
867        if self
868            .text
869            .len()
870            .checked_add(additional)
871            .is_none_or(|length| length > self.max_bytes)
872        {
873            Err(Error::build(
874                ErrorKind::ResourceLimit,
875                "Built S-expression output exceeds max_output_bytes",
876            ))
877        } else {
878            Ok(())
879        }
880    }
881}
882
883impl fmt::Write for BuildOutput {
884    fn write_str(&mut self, value: &str) -> fmt::Result {
885        self.push_str(value).map_err(|_| fmt::Error)
886    }
887}
888
889fn build_into(value: &Sexp, indent: &str, output: &mut BuildOutput) -> Result<(), Error> {
890    match value {
891        Sexp::List(values) => {
892            output.push('(')?;
893            let mut last_was_list = false;
894            for (index, child) in values.iter().enumerate() {
895                if index > 0 {
896                    if matches!(child, Sexp::List(_)) {
897                        output.push_str("\n\t")?;
898                        output.push_str(indent)?;
899                    } else {
900                        output.push(' ')?;
901                    }
902                }
903                let mut child_indent = String::with_capacity(indent.len() + 1);
904                child_indent.push_str(indent);
905                child_indent.push('\t');
906                build_into(child, &child_indent, output)?;
907                last_was_list = matches!(child, Sexp::List(_));
908            }
909            if last_was_list {
910                output.push('\n')?;
911                output.push_str(indent)?;
912            }
913            output.push(')')?;
914            Ok(())
915        }
916        Sexp::Atom(value) => {
917            if value.is_empty() {
918                output.push_str("\"\"")?;
919            } else if value
920                .chars()
921                .any(|character| character.is_whitespace() || matches!(character, '(' | ')'))
922                || value.starts_with('"')
923            {
924                output.push('"')?;
925                escape_quoted_into(value, output)?;
926                output.push('"')?;
927            } else {
928                output.push_str(value)?;
929            }
930            Ok(())
931        }
932        Sexp::Quoted(value) => {
933            output.push('"')?;
934            escape_quoted_into(value, output)?;
935            output.push('"')?;
936            Ok(())
937        }
938        Sexp::Integer(value) => write!(output, "{value}").map_err(|_| build_output_error()),
939        Sexp::Float(value) => {
940            if !value.is_finite() {
941                return Err(Error::build(
942                    ErrorKind::InvalidBuildValue,
943                    "Cannot build a non-finite float",
944                ));
945            }
946            if *value == 0.0 {
947                output.push('0')?;
948            } else {
949                write!(output, "{value}").map_err(|_| build_output_error())?;
950            }
951            Ok(())
952        }
953    }
954}
955
956fn build_output_error() -> Error {
957    Error::build(
958        ErrorKind::ResourceLimit,
959        "Built S-expression output exceeds max_output_bytes",
960    )
961}
962
963fn escape_quoted_into(value: &str, output: &mut BuildOutput) -> Result<(), Error> {
964    for character in value.chars() {
965        match character {
966            '\n' => output.push_str("\\n")?,
967            '\r' => output.push_str("\\r")?,
968            '\\' => output.push_str("\\\\")?,
969            '"' => output.push_str("\\\"")?,
970            _ => output.push(character)?,
971        }
972    }
973    Ok(())
974}
975
976pub(crate) fn decode_quoted(lexeme: &str) -> String {
977    decode_quoted_with_limit(lexeme, usize::MAX).unwrap_or_default()
978}
979
980#[allow(
981    clippy::cognitive_complexity,
982    reason = "pre-standard bounded escape decoder retained under the structural ratchet"
983)]
984pub(crate) fn decode_quoted_with_limit(lexeme: &str, max_bytes: usize) -> Option<String> {
985    let body = &lexeme[1..lexeme.len() - 1];
986    let mut output = String::with_capacity(body.len().min(max_bytes));
987    let mut characters = body.chars().peekable();
988
989    while let Some(mut character) = characters.next() {
990        if character == '\r' {
991            if characters.peek() == Some(&'\n') {
992                characters.next();
993            }
994            character = '\n';
995        }
996        if character != '\\' {
997            output.push(character);
998        } else {
999            let Some(mut next) = characters.next() else {
1000                output.push('\\');
1001                return (output.len() <= max_bytes).then_some(output);
1002            };
1003            if next == '\r' {
1004                if characters.peek() == Some(&'\n') {
1005                    characters.next();
1006                }
1007                next = '\n';
1008            }
1009            match next {
1010                '"' | '\\' => output.push(next),
1011                'a' => output.push('\u{0007}'),
1012                'b' => output.push('\u{0008}'),
1013                'f' => output.push('\u{000c}'),
1014                'n' => output.push('\n'),
1015                'r' => output.push('\r'),
1016                't' => output.push('\t'),
1017                'v' => output.push('\u{000b}'),
1018                'x' => {
1019                    let mut digits = String::new();
1020                    for _ in 0..2 {
1021                        match characters.peek().copied() {
1022                            Some(digit) if digit.is_ascii_hexdigit() => {
1023                                digits.push(digit);
1024                                characters.next();
1025                            }
1026                            _ => break,
1027                        }
1028                    }
1029                    if digits.is_empty() {
1030                        output.push('x');
1031                    } else if let Ok(value) = u8::from_str_radix(&digits, 16) {
1032                        output.push(char::from(value));
1033                    }
1034                }
1035                digit @ '0'..='7' => {
1036                    let mut digits = String::from(digit);
1037                    for _ in 1..3 {
1038                        match characters.peek().copied() {
1039                            Some(next_digit @ '0'..='7') => {
1040                                digits.push(next_digit);
1041                                characters.next();
1042                            }
1043                            _ => break,
1044                        }
1045                    }
1046                    if let Ok(value) = u8::from_str_radix(&digits, 8) {
1047                        output.push(char::from(value));
1048                    }
1049                }
1050                other => {
1051                    output.push('\\');
1052                    output.push(other);
1053                }
1054            }
1055        }
1056        if output.len() > max_bytes {
1057            return None;
1058        }
1059    }
1060    Some(output)
1061}
1062
1063fn classify_bare_token(token: &str) -> TokenKind {
1064    if !matches_number_grammar(token) {
1065        return TokenKind::Atom;
1066    }
1067    if token.contains('.') || token.contains('e') || token.contains('E') {
1068        TokenKind::Float
1069    } else {
1070        TokenKind::Integer
1071    }
1072}
1073
1074fn matches_number_grammar(token: &str) -> bool {
1075    let bytes = token.as_bytes();
1076    if bytes.is_empty() {
1077        return false;
1078    }
1079    let mut index = usize::from(matches!(bytes[0], b'+' | b'-'));
1080    if index >= bytes.len() {
1081        return false;
1082    }
1083
1084    let digits_before = consume_digits(bytes, &mut index);
1085    let mut digits_after = 0;
1086    if index < bytes.len() && bytes[index] == b'.' {
1087        index += 1;
1088        digits_after = consume_digits(bytes, &mut index);
1089    }
1090    if digits_before == 0 && digits_after == 0 {
1091        return false;
1092    }
1093
1094    if index < bytes.len() && matches!(bytes[index], b'e' | b'E') {
1095        index += 1;
1096        if index < bytes.len() && matches!(bytes[index], b'+' | b'-') {
1097            index += 1;
1098        }
1099        if consume_digits(bytes, &mut index) == 0 {
1100            return false;
1101        }
1102    }
1103    index == bytes.len()
1104}
1105
1106fn consume_digits(bytes: &[u8], index: &mut usize) -> usize {
1107    let start = *index;
1108    while *index < bytes.len() && bytes[*index].is_ascii_digit() {
1109        *index += 1;
1110    }
1111    *index - start
1112}
1113
1114fn is_teardrop_field_key(token: &Token<'_>) -> bool {
1115    token.kind == TokenKind::Atom
1116        && (is_teardrop_numeric_key(token.lexeme) || is_teardrop_bool_key(token.lexeme))
1117}
1118
1119pub(crate) fn is_teardrop_numeric_key(key: &str) -> bool {
1120    matches!(
1121        key,
1122        "best_length_ratio"
1123            | "max_length"
1124            | "best_width_ratio"
1125            | "max_width"
1126            | "curve_points"
1127            | "filter_ratio"
1128    )
1129}
1130
1131pub(crate) fn is_teardrop_bool_key(key: &str) -> bool {
1132    matches!(
1133        key,
1134        "enabled" | "allow_two_segments" | "prefer_zone_connections" | "curved_edges"
1135    )
1136}
1137
1138fn position_at_valid_prefix(prefix: &[u8]) -> Position {
1139    let Ok(text) = std::str::from_utf8(prefix) else {
1140        return Position {
1141            offset: prefix.len(),
1142            line: 1,
1143            column: 1,
1144        };
1145    };
1146    let mut lexer = Lexer::new(text);
1147    lexer.advance_to(text.len());
1148    lexer.position()
1149}
1150
1151fn position_at_text_offset(source: &str, offset: usize) -> Position {
1152    let mut lexer = Lexer::new(source);
1153    lexer.advance_to(offset);
1154    lexer.position()
1155}