From f4a1e3bae9e970c0d54f75936ac1a3488e8e73ec Mon Sep 17 00:00:00 2001 From: youknowdot Date: Sun, 29 Nov 2026 23:10:45 +0900 Subject: [PATCH] Parse interactive single input with its own start rule Assisted-by: Codex:unspecified --- crates/ruff_python_parser/src/error.rs | 5 +- crates/ruff_python_parser/src/lexer.rs | 52 ++++++++++++- crates/ruff_python_parser/src/lib.rs | 6 +- crates/ruff_python_parser/src/parser/mod.rs | 76 ++++++++++++++++++- .../ruff_python_parser/src/parser/options.rs | 10 +++ .../src/parser/statement.rs | 8 +- crates/ruff_python_parser/src/parser/tests.rs | 21 +++++ crates/ruff_python_parser/src/token_source.rs | 10 ++- 8 files changed, 179 insertions(+), 9 deletions(-) diff --git a/crates/ruff_python_parser/src/error.rs b/crates/ruff_python_parser/src/error.rs index 10fb5b92b9edb..e8ff1f0a789db 100644 --- a/crates/ruff_python_parser/src/error.rs +++ b/crates/ruff_python_parser/src/error.rs @@ -354,6 +354,9 @@ pub enum ParseErrorType { /// An unexpected token was found at the end of an expression parsing UnexpectedExpressionToken, + /// The interactive start rule cannot consume the current token. + InvalidInteractiveInput, + /// An f-string error containing the [`InterpolatedStringErrorType`]. FStringError(InterpolatedStringErrorType), /// A t-string error containing the [`InterpolatedStringErrorType`]. @@ -747,7 +750,7 @@ impl std::fmt::Display for ParseErrorType { ParseErrorType::TStringError(error) => { write_interpolated_string_error(f, InterpolatedStringKind::TString, error) } - ParseErrorType::UnexpectedExpressionToken => f.write_str("invalid syntax"), + ParseErrorType::UnexpectedExpressionToken | ParseErrorType::InvalidInteractiveInput => f.write_str("invalid syntax"), } } } diff --git a/crates/ruff_python_parser/src/lexer.rs b/crates/ruff_python_parser/src/lexer.rs index 5a0e3c29639ca..65153ebcfb855 100644 --- a/crates/ruff_python_parser/src/lexer.rs +++ b/crates/ruff_python_parser/src/lexer.rs @@ -73,6 +73,9 @@ pub struct Lexer<'src> { /// Lexer mode. mode: Mode, + dont_imply_dedent: bool, + single_parsing_started: bool, + single_eof_dedents: bool, /// F-string and t-string contexts. interpolated_strings: InterpolatedStrings, @@ -111,6 +114,9 @@ impl<'src> Lexer<'src> { indentations: Indentations::default(), pending_indentation: None, mode, + dont_imply_dedent: false, + single_parsing_started: false, + single_eof_dedents: false, interpolated_strings: InterpolatedStrings::default(), errors: Vec::new(), }; @@ -125,6 +131,11 @@ impl<'src> Lexer<'src> { lexer } + pub(crate) fn with_dont_imply_dedent(mut self, dont_imply_dedent: bool) -> Self { + self.dont_imply_dedent = dont_imply_dedent; + self + } + /// Returns the kind of the current token. pub(crate) const fn current_kind(&self) -> TokenKind { self.current_kind @@ -178,6 +189,13 @@ impl<'src> Lexer<'src> { // `lex_token` marks the start on the path that lexes each token. self.current_flags = TokenFlags::empty(); self.current_kind = self.lex_token(); + if self.mode == Mode::Single + && !self.current_kind.is_trivia() + && !matches!(self.current_kind, TokenKind::EndOfFile) + && !self.single_eof_dedents + { + self.single_parsing_started = true; + } // For `Unknown` token, the `push_error` method updates the current range. if !matches!(self.current_kind, TokenKind::Unknown) { self.current_range = self.token_range(); @@ -322,7 +340,11 @@ impl<'src> Lexer<'src> { } // Handle indentation if this is a new, not all empty, logical line - if !matches!(self.cursor.first(), '\n' | '\r' | '#' | EOF_CHAR) { + if !matches!(self.cursor.first(), '\n' | '\r' | '#' | EOF_CHAR) + || (self.mode == Mode::Single + && self.cursor.is_eof() + && self.current_kind != TokenKind::Comment) + { self.state = State::NonEmptyLogicalLine; // Set to false so that we don't handle indentation on the next call. @@ -1481,6 +1503,26 @@ impl<'src> Lexer<'src> { return TokenKind::Unknown; } + if self.mode == Mode::Single { + // CPython's interactive token feed turns an end marker into a + // newline and queues the implied dedents, in that order. + if self.single_eof_dedents { + if !self.dont_imply_dedent && self.indentations.dedent().is_some() { + self.single_parsing_started = true; + return TokenKind::Dedent; + } + self.single_eof_dedents = false; + } + if self.single_parsing_started { + // Set the flag even when there are no dedents; it also keeps + // next_token() from treating this synthetic newline as input. + self.single_eof_dedents = true; + self.single_parsing_started = false; + return TokenKind::Newline; + } + return TokenKind::EndOfFile; + } + // Next, insert a trailing newline, if required. if !self.state.is_new_logical_line() { self.state = State::AfterNewline; @@ -1727,6 +1769,8 @@ impl<'src> Lexer<'src> { brackets: self.brackets.clone(), indentations_checkpoint: self.indentations.checkpoint(), pending_indentation: self.pending_indentation, + single_parsing_started: self.single_parsing_started, + single_eof_dedents: self.single_eof_dedents, interpolated_strings_checkpoint: self.interpolated_strings.checkpoint(), errors_position: self.errors.len(), } @@ -1744,6 +1788,8 @@ impl<'src> Lexer<'src> { brackets, indentations_checkpoint, pending_indentation, + single_parsing_started, + single_eof_dedents, interpolated_strings_checkpoint, errors_position, } = checkpoint; @@ -1761,6 +1807,8 @@ impl<'src> Lexer<'src> { self.brackets = brackets; self.indentations.rewind(indentations_checkpoint); self.pending_indentation = pending_indentation; + self.single_parsing_started = single_parsing_started; + self.single_eof_dedents = single_eof_dedents; self.interpolated_strings .rewind(interpolated_strings_checkpoint); self.errors.truncate(errors_position); @@ -1810,6 +1858,8 @@ pub(crate) struct LexerCheckpoint { brackets: Vec, indentations_checkpoint: IndentationsCheckpoint, pending_indentation: Option, + single_parsing_started: bool, + single_eof_dedents: bool, interpolated_strings_checkpoint: InterpolatedStringsCheckpoint, errors_position: usize, } diff --git a/crates/ruff_python_parser/src/lib.rs b/crates/ruff_python_parser/src/lib.rs index 9d7887e1cc4d0..72856b9582fd6 100644 --- a/crates/ruff_python_parser/src/lib.rs +++ b/crates/ruff_python_parser/src/lib.rs @@ -626,6 +626,9 @@ pub enum Mode { /// The code consists of a sequence of statements. Module, + /// One interactive input: a simple statement group or a compound statement plus newline. + Single, + /// The code consists of a single expression. Expression, @@ -657,7 +660,8 @@ impl std::str::FromStr for Mode { type Err = ModeParseError; fn from_str(s: &str) -> Result { match s { - "exec" | "single" => Ok(Mode::Module), + "exec" => Ok(Mode::Module), + "single" => Ok(Mode::Single), "eval" => Ok(Mode::Expression), "ipython" => Ok(Mode::Ipython), _ => Err(ModeParseError), diff --git a/crates/ruff_python_parser/src/parser/mod.rs b/crates/ruff_python_parser/src/parser/mod.rs index 0dd5bf8db563d..e476da76f6fbe 100644 --- a/crates/ruff_python_parser/src/parser/mod.rs +++ b/crates/ruff_python_parser/src/parser/mod.rs @@ -8,7 +8,7 @@ use ruff_python_ast::name::Name; use ruff_python_ast::token::TokenKind; use ruff_python_ast::{ Alias, AtomicNodeIndex, ElifElseClause, Expr, Int, IpyEscapeKind, Keyword, Mod, ModExpression, - ModModule, ParameterWithDefault, Stmt, StringFlags, + ModModule, ParameterWithDefault, Stmt, StringFlags, Suite, }; use ruff_python_trivia::is_python_whitespace; use ruff_text_size::{Ranged, TextRange, TextSize}; @@ -160,7 +160,12 @@ impl<'src> Parser<'src> { start_offset: TextSize, options: ParseOptions, ) -> Self { - let tokens = TokenSource::from_source(source, options.mode, start_offset); + let tokens = TokenSource::from_source( + source, + options.mode, + start_offset, + options.dont_imply_dedent, + ); Parser { options, @@ -241,6 +246,7 @@ impl<'src> Parser<'src> { Mod::Expression(parser.parse_single_expression()) } Mode::Module | Mode::Ipython => Mod::Module(parser.parse_module()), + Mode::Single => Mod::Module(parser.parse_interactive()), }); self.finish(syntax) @@ -287,6 +293,72 @@ impl<'src> Parser<'src> { } } + /// Parses the interactive start rule before any compiler or AST validation. + fn parse_interactive(&mut self) -> ModModule { + // Even the single-input rule needs the enclosing statement recovery + // boundaries for errors inside a list, import, or suite. + self.recovery_context = RecoveryContext::from_kind(RecoveryContextKind::ModuleStatements); + let mut body = Suite::new(); + if self.at(TokenKind::Indent) { + self.add_error( + ParseErrorType::UnexpectedIndentation, + self.current_token_range(), + ); + } else if self.at(TokenKind::EndOfFile) { + self.add_error( + ParseErrorType::InvalidInteractiveInput, + self.current_token_range(), + ); + } else if !self.eat(TokenKind::Newline) { + let stmt = self.parse_statement(); + let compound = matches!( + &stmt, + Stmt::FunctionDef(_) + | Stmt::ClassDef(_) + | Stmt::For(_) + | Stmt::While(_) + | Stmt::If(_) + | Stmt::With(_) + | Stmt::Match(_) + | Stmt::Try(_) + ); + body.push(stmt); + if compound { + if !self.eat(TokenKind::Newline) || !self.at(TokenKind::EndOfFile) { + self.add_error( + ParseErrorType::InvalidInteractiveInput, + self.current_token_range(), + ); + } + } else { + let mut progress = ParserProgress::default(); + while self.tokens.previous_kind() == Some(TokenKind::Semi) + && !self.at(TokenKind::EndOfFile) + { + progress.assert_progressing(self); + body.push(self.parse_single_simple_statement()); + } + if self.tokens.previous_kind() != Some(TokenKind::Newline) { + self.add_error( + ParseErrorType::InvalidInteractiveInput, + self.current_token_range(), + ); + } + } + } + + while !self.at(TokenKind::EndOfFile) { + self.bump_any(); + } + self.bump(TokenKind::EndOfFile); + ModModule { + body, + range: TextRange::new(self.start_offset, self.current_token_range().end()), + node_index: AtomicNodeIndex::NONE, + runtime_body: None, + } + } + /// Parses a Python module. /// /// This is to be used for [`Mode::Module`] and [`Mode::Ipython`]. diff --git a/crates/ruff_python_parser/src/parser/options.rs b/crates/ruff_python_parser/src/parser/options.rs index ec87a72d1e481..75fac745b59dd 100644 --- a/crates/ruff_python_parser/src/parser/options.rs +++ b/crates/ruff_python_parser/src/parser/options.rs @@ -24,11 +24,19 @@ use crate::{AsMode, Mode}; pub struct ParseOptions { /// Specify the mode in which the code will be parsed. pub(crate) mode: Mode, + pub(crate) dont_imply_dedent: bool, /// Target version for detecting version-related syntax errors. pub(crate) target_version: PythonVersion, } impl ParseOptions { + /// In single-input mode, do not close a suite on an implied newline. + #[must_use] + pub fn with_dont_imply_dedent(mut self, dont_imply_dedent: bool) -> Self { + self.dont_imply_dedent = dont_imply_dedent; + self + } + #[must_use] pub fn with_target_version(mut self, target_version: PythonVersion) -> Self { self.target_version = target_version; @@ -44,6 +52,7 @@ impl From for ParseOptions { fn from(mode: Mode) -> Self { Self { mode, + dont_imply_dedent: false, target_version: PythonVersion::default(), } } @@ -53,6 +62,7 @@ impl From for ParseOptions { fn from(source_type: PySourceType) -> Self { Self { mode: source_type.as_mode(), + dont_imply_dedent: false, target_version: PythonVersion::default(), } } diff --git a/crates/ruff_python_parser/src/parser/statement.rs b/crates/ruff_python_parser/src/parser/statement.rs index 201d72c0ff3d7..ac55b2c7e812b 100644 --- a/crates/ruff_python_parser/src/parser/statement.rs +++ b/crates/ruff_python_parser/src/parser/statement.rs @@ -164,7 +164,7 @@ impl<'src> Parser<'src> { /// This statement must be terminated by a newline or semicolon. /// /// Use [`Parser::parse_simple_statements`] to parse a sequence of simple statements. - fn parse_single_simple_statement(&mut self) -> Stmt { + pub(super) fn parse_single_simple_statement(&mut self) -> Stmt { let stmt = self.parse_simple_statement(); // The order of the token is important here. @@ -3558,7 +3558,11 @@ impl<'src> Parser<'src> { parser.stmt_scratch.take_thin_vec(snapshot) }); - self.expect(TokenKind::Dedent); + if self.options.mode == Mode::Single && self.at(TokenKind::EndOfFile) { + self.add_error(ParseErrorType::InvalidInteractiveInput, self.current_token_range()); + } else { + self.expect(TokenKind::Dedent); + } statements } diff --git a/crates/ruff_python_parser/src/parser/tests.rs b/crates/ruff_python_parser/src/parser/tests.rs index 9772b2158edca..5a2af78f34356 100644 --- a/crates/ruff_python_parser/src/parser/tests.rs +++ b/crates/ruff_python_parser/src/parser/tests.rs @@ -639,3 +639,24 @@ fn non_printable_character() { "invalid non-printable character U+00A0" ); } + +#[test] +fn interactive_start_rule_requires_compound_terminator() { + for (source, dont_imply_dedent, valid) in [ + ("x = 1; x = 2", false, true), + ("if 1: pass", false, false), + ("if 1: pass\n", true, true), + ("if 1:\n pass", false, true), + ("if 1:\n pass", true, false), + ("if 1:\n pass\n", true, true), + ("if 1:\n if 2:\n pass", false, true), + ("if 1:\n pass\nelse: pass", false, false), + ("if 1: pass\nnext = 1", false, false), + ] { + let options = ParseOptions::from(Mode::Single).with_dont_imply_dedent(dont_imply_dedent); + assert_eq!(parse(source, options).is_ok(), valid, "{source:?}"); + } + + assert!(parse_module("if 1: pass").is_ok()); + assert!(parse_module("if 1: pass\nnext = 1").is_ok()); +} diff --git a/crates/ruff_python_parser/src/token_source.rs b/crates/ruff_python_parser/src/token_source.rs index ac2f3f0dbdc90..4241d07f7b394 100644 --- a/crates/ruff_python_parser/src/token_source.rs +++ b/crates/ruff_python_parser/src/token_source.rs @@ -28,8 +28,14 @@ impl<'src> TokenSource<'src> { } /// Create a new token source from the given source code which starts at the given offset. - pub(crate) fn from_source(source: &'src str, mode: Mode, start_offset: TextSize) -> Self { - let lexer = Lexer::new(source, mode, start_offset); + pub(crate) fn from_source( + source: &'src str, + mode: Mode, + start_offset: TextSize, + dont_imply_dedent: bool, + ) -> Self { + let lexer = + Lexer::new(source, mode, start_offset).with_dont_imply_dedent(dont_imply_dedent); let mut source = TokenSource::new(lexer, source, start_offset); // Initialize the token source so that the current token is set correctly.