Skip to main content

mago_syntax/parser/
mod.rs

1use mago_allocator::prelude::*;
2
3use mago_database::file::File;
4use mago_database::file::FileId;
5use mago_database::file::HasFileId;
6use mago_span::{Position, Span};
7use mago_syntax_core::input::Input;
8
9use crate::cst::Program;
10use crate::cst::sequence::Sequence;
11use crate::error::ParseError;
12use crate::lexer::Lexer;
13use crate::parser::stream::TokenStream;
14use crate::settings::ParserSettings;
15use crate::token::TokenKind;
16
17mod internal;
18
19pub mod stream;
20
21/// Maximum recursion depth for expression parsing.
22/// This prevents stack overflow on deeply nested expressions and statements.
23const MAX_RECURSION_DEPTH: u16 = 512;
24
25#[derive(Debug, Default)]
26pub struct State {
27    pub within_string_interpolation: bool,
28    pub recursion_depth: u16,
29}
30
31/// The main parser for PHP source code.
32///
33/// The parser holds an arena reference, the token stream, and parsing state.
34#[derive(Debug)]
35#[allow(clippy::field_scoped_visibility_modifiers)]
36pub struct Parser<'input, 'arena, A>
37where
38    'input: 'arena,
39    A: Arena,
40{
41    pub(crate) arena: &'arena A,
42    pub(crate) state: State,
43    pub(crate) stream: TokenStream<'input, 'arena, A>,
44    pub(crate) errors: Vec<'arena, ParseError, A>,
45    pub(crate) recovery_end: Option<Span>,
46}
47
48impl<'input, 'arena, A> Parser<'input, 'arena, A>
49where
50    A: Arena,
51{
52    /// Creates a new parser for the given content.
53    ///
54    /// # Parameters
55    ///
56    /// - `arena`: The memory arena for allocations.
57    /// - `file_id`: The ID of the file being parsed.
58    /// - `content`: The content to parse.
59    /// - `settings`: The parser settings.
60    ///
61    /// # Returns
62    ///
63    /// A new `Parser` instance.
64    #[inline]
65    pub fn new(arena: &'arena A, file_id: FileId, content: &'input [u8], settings: ParserSettings) -> Self {
66        let input = Input::new(file_id, content);
67        let lexer = Lexer::new(input, settings.lexer);
68        let stream = TokenStream::new(arena, lexer);
69
70        let end = Position::new(content.len() as u32);
71        let recovery_end = settings.recover_incomplete.then_some(Span::new(file_id, end, end));
72        Self { arena, state: State::default(), stream, errors: Vec::new_in(arena), recovery_end }
73    }
74
75    fn recover_at_eof(&mut self, error: ParseError) -> Result<Span, ParseError> {
76        if let Some(end) = self.recovery_end
77            && matches!(error, ParseError::UnexpectedEndOfFile(..))
78        {
79            self.errors.push(error);
80            Ok(end)
81        } else {
82            Err(error)
83        }
84    }
85
86    fn parse_closing_span(&mut self, kind: TokenKind) -> Result<Span, ParseError> {
87        match self.stream.eat_span(kind) {
88            Ok(span) => Ok(span),
89            Err(error) => self.recover_at_eof(error),
90        }
91    }
92
93    /// Creates a new parser for the given file.
94    ///
95    /// # Parameters
96    ///
97    /// - `arena`: The memory arena for allocations.
98    /// - `file`: The file to parse.
99    /// - `settings`: The parser settings.
100    ///
101    /// # Returns
102    ///
103    /// A new `Parser` instance.
104    pub fn for_file(arena: &'arena A, file: &'input File, settings: ParserSettings) -> Self {
105        Self::new(arena, file.file_id(), file.contents.as_ref(), settings)
106    }
107
108    /// Parses and returns the program CST.
109    fn parse(mut self, source_text: &'arena [u8], file_id: FileId) -> &'arena Program<'arena> {
110        let mut statements = Vec::new_in(self.arena);
111
112        loop {
113            let reached_eof = match self.stream.has_reached_eof() {
114                Ok(eof) => eof,
115                Err(err) => {
116                    self.errors.push(ParseError::from(err));
117                    break;
118                }
119            };
120
121            if reached_eof {
122                break;
123            }
124
125            // Record position before parsing to detect infinite loops
126            let position_before = self.stream.current_position();
127
128            match self.parse_statement() {
129                Ok(statement) => statements.push(statement),
130                Err(err) => self.errors.push(err),
131            }
132
133            // Safety check: if we didn't advance at all, skip a token to prevent infinite loop.
134            // This can happen with orphan keywords like `finally`, `catch`, `else`, etc.
135            // that are preserved by the expression parser but not handled by the statement parser.
136            let position_after = self.stream.current_position();
137            if position_after == position_before
138                && let Ok(Some(token)) = self.stream.lookahead(0)
139            {
140                self.errors.push(self.stream.unexpected(Some(token), &[]));
141                let _ = self.stream.consume();
142            }
143        }
144
145        self.arena.alloc(Program {
146            file_id,
147            source_text,
148            statements: Sequence::new(statements),
149            trivia: self.stream.get_trivia(),
150            errors: self.errors.leak(),
151        })
152    }
153}
154
155/// Parses the given file and returns the program CST.
156///
157/// # Parameters
158///
159/// - `arena`: The memory arena for allocations.
160/// - `file`: The file to parse.
161///
162/// # Returns
163///
164/// The parsed `Program` CST.
165#[inline]
166pub fn parse_file<'arena, A>(arena: &'arena A, file: &File) -> &'arena Program<'arena>
167where
168    A: Arena,
169{
170    parse_file_content(arena, file.file_id(), file.contents.as_ref())
171}
172
173/// Parses the given file with custom settings and returns the program CST.
174///
175/// # Parameters
176///
177/// - `arena`: The memory arena for allocations.
178/// - `file`: The file to parse.
179/// - `settings`: The parser settings.
180///
181/// # Returns
182///
183/// The parsed `Program` CST.
184#[inline]
185pub fn parse_file_with_settings<'arena, A>(
186    arena: &'arena A,
187    file: &File,
188    settings: ParserSettings,
189) -> &'arena Program<'arena>
190where
191    A: Arena,
192{
193    parse_file_content_with_settings(arena, file.file_id(), file.contents.as_ref(), settings)
194}
195
196/// Parses a file without copying its source bytes into the arena.
197///
198/// The file must remain alive while the returned program is in use.
199#[inline]
200pub fn parse_file_borrowed_with_settings<'arena, A>(
201    arena: &'arena A,
202    file: &'arena File,
203    settings: ParserSettings,
204) -> &'arena Program<'arena>
205where
206    A: Arena,
207{
208    Parser::for_file(arena, file, settings).parse(file.contents.as_ref(), file.file_id())
209}
210
211/// Parses the given file content and returns the program CST.
212///
213/// # Parameters
214///
215/// - `arena`: The memory arena for allocations.
216/// - `file_id`: The ID of the file being parsed.
217/// - `content`: The content to parse.
218///
219/// # Returns
220///
221/// The parsed `Program` CST.
222pub fn parse_file_content<'arena, A>(arena: &'arena A, file_id: FileId, content: &[u8]) -> &'arena Program<'arena>
223where
224    A: Arena,
225{
226    let source_text = arena.alloc_slice_copy(content);
227    Parser::new(arena, file_id, source_text, ParserSettings::default()).parse(source_text, file_id)
228}
229
230/// Parses the given file content with custom settings and returns the program CST.
231///
232/// # Parameters
233///
234/// - `arena`: The memory arena for allocations.
235/// - `file_id`: The ID of the file being parsed.
236/// - `content`: The content to parse.
237/// - `settings`: The parser settings.
238///
239/// # Returns
240///
241/// The parsed `Program` CST.
242pub fn parse_file_content_with_settings<'arena, A>(
243    arena: &'arena A,
244    file_id: FileId,
245    content: &[u8],
246    settings: ParserSettings,
247) -> &'arena Program<'arena>
248where
249    A: Arena,
250{
251    let source_text = arena.alloc_slice_copy(content);
252    Parser::new(arena, file_id, source_text, settings).parse(source_text, file_id)
253}