Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/ruff_python_parser/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`].
Expand Down Expand Up @@ -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"),
}
}
}
Expand Down
52 changes: 51 additions & 1 deletion crates/ruff_python_parser/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(),
};
Expand All @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
}
Expand All @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -1810,6 +1858,8 @@ pub(crate) struct LexerCheckpoint {
brackets: Vec<OpenBracket>,
indentations_checkpoint: IndentationsCheckpoint,
pending_indentation: Option<Indentation>,
single_parsing_started: bool,
single_eof_dedents: bool,
interpolated_strings_checkpoint: InterpolatedStringsCheckpoint,
errors_position: usize,
}
Expand Down
6 changes: 5 additions & 1 deletion crates/ruff_python_parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down Expand Up @@ -657,7 +660,8 @@ impl std::str::FromStr for Mode {
type Err = ModeParseError;
fn from_str(s: &str) -> Result<Self, ModeParseError> {
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),
Expand Down
76 changes: 74 additions & 2 deletions crates/ruff_python_parser/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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`].
Expand Down
10 changes: 10 additions & 0 deletions crates/ruff_python_parser/src/parser/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -44,6 +52,7 @@ impl From<Mode> for ParseOptions {
fn from(mode: Mode) -> Self {
Self {
mode,
dont_imply_dedent: false,
target_version: PythonVersion::default(),
}
}
Expand All @@ -53,6 +62,7 @@ impl From<PySourceType> for ParseOptions {
fn from(source_type: PySourceType) -> Self {
Self {
mode: source_type.as_mode(),
dont_imply_dedent: false,
target_version: PythonVersion::default(),
}
}
Expand Down
8 changes: 6 additions & 2 deletions crates/ruff_python_parser/src/parser/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
21 changes: 21 additions & 0 deletions crates/ruff_python_parser/src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
10 changes: 8 additions & 2 deletions crates/ruff_python_parser/src/token_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading