1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! Python code compilation functions.
//!
//! For code execution functions, see python_run.rs
use crate::{
PyRef, VirtualMachine,
builtins::PyCode,
compiler::{self, CompileError, CompileOpts},
};
impl VirtualMachine {
pub fn compile(
&self,
source: &str,
mode: compiler::Mode,
source_path: String,
) -> Result<PyRef<PyCode>, CompileError> {
self.compile_with_opts(source, mode, source_path, self.compile_opts())
}
pub fn compile_with_opts(
&self,
source: &str,
mode: compiler::Mode,
source_path: String,
opts: CompileOpts,
) -> Result<PyRef<PyCode>, CompileError> {
let code =
compiler::compile(source, mode, &source_path, opts).map(|code| self.ctx.new_code(code));
#[cfg(feature = "parser")]
if code.is_ok() {
self.emit_string_escape_warnings(source, &source_path);
}
code
}
}
/// Scan source for invalid escape sequences in all string literals and emit
/// SyntaxWarning.
///
/// Corresponds to:
/// - `warn_invalid_escape_sequence()` in `Parser/string_parser.c`
/// - `_PyTokenizer_warn_invalid_escape_sequence()` in `Parser/tokenizer/helpers.c`
#[cfg(feature = "parser")]
mod escape_warnings {
use super::*;
use crate::warn;
use ruff_python_ast::{self as ast, visitor::Visitor};
use ruff_text_size::TextRange;
/// Calculate 1-indexed line number at byte offset in source.
fn line_number_at(source: &str, offset: usize) -> usize {
source[..offset.min(source.len())]
.bytes()
.filter(|&b| b == b'\n')
.count()
+ 1
}
/// Get content bounds (start, end byte offsets) of a quoted string literal,
/// excluding prefix characters and quote delimiters.
fn content_bounds(source: &str, range: TextRange) -> Option<(usize, usize)> {
let s = range.start().to_usize();
let e = range.end().to_usize();
if s >= e || e > source.len() {
return None;
}
let bytes = &source.as_bytes()[s..e];
// Skip prefix (u, b, r, etc.) to find the first quote character.
let qi = bytes.iter().position(|&c| c == b'\'' || c == b'"')?;
let qc = bytes[qi];
let ql = if bytes.get(qi + 1) == Some(&qc) && bytes.get(qi + 2) == Some(&qc) {
3
} else {
1
};
let cs = s + qi + ql;
let ce = e.checked_sub(ql)?;
if cs <= ce { Some((cs, ce)) } else { None }
}
/// Scan `source[start..end]` for the first invalid escape sequence.
/// Returns `Some((invalid_char, byte_offset_in_source))` for the first
/// invalid escape found, or `None` if all escapes are valid.
///
/// When `is_bytes` is true, `\u`, `\U`, and `\N` are treated as invalid
/// (bytes literals only support byte-oriented escapes).
///
/// Only reports the **first** invalid escape per string literal, matching
/// `_PyUnicode_DecodeUnicodeEscapeInternal2` which stores only the first
/// `first_invalid_escape_char`.
fn first_invalid_escape(
source: &str,
start: usize,
end: usize,
is_bytes: bool,
) -> Option<(char, usize)> {
let raw = &source[start..end];
let mut chars = raw.char_indices().peekable();
while let Some((i, ch)) = chars.next() {
if ch != '\\' {
continue;
}
let Some((_, next)) = chars.next() else {
break;
};
let valid = match next {
'\\' | '\'' | '"' | 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' => true,
'\n' => true,
'\r' => {
if matches!(chars.peek(), Some(&(_, '\n'))) {
chars.next();
}
true
}
'0'..='7' => {
for _ in 0..2 {
if matches!(chars.peek(), Some(&(_, '0'..='7'))) {
chars.next();
} else {
break;
}
}
true
}
'x' | 'u' | 'U' => {
// \u and \U are only valid in string literals, not bytes
if is_bytes && next != 'x' {
false
} else {
let count = match next {
'x' => 2,
'u' => 4,
'U' => 8,
_ => unreachable!(),
};
for _ in 0..count {
if chars.peek().is_some_and(|&(_, c)| c.is_ascii_hexdigit()) {
chars.next();
} else {
break;
}
}
true
}
}
'N' => {
// \N{name} is only valid in string literals, not bytes
if is_bytes {
false
} else {
if matches!(chars.peek(), Some(&(_, '{'))) {
chars.next();
for (_, c) in chars.by_ref() {
if c == '}' {
break;
}
}
}
true
}
}
_ => false,
};
if !valid {
return Some((next, start + i));
}
}
None
}
/// Emit `SyntaxWarning` for an invalid escape sequence.
///
/// `warn_invalid_escape_sequence()` in `Parser/string_parser.c`
fn warn_invalid_escape_sequence(
source: &str,
ch: char,
offset: usize,
filename: &str,
vm: &VirtualMachine,
) {
let lineno = line_number_at(source, offset);
let message = vm.ctx.new_str(format!(
"\"\\{ch}\" is an invalid escape sequence. \
Such sequences will not work in the future. \
Did you mean \"\\\\{ch}\"? A raw string is also an option."
));
let fname = vm.ctx.new_str(filename);
let _ = warn::warn_explicit(
Some(vm.ctx.exceptions.syntax_warning.to_owned()),
message.into(),
fname,
lineno,
None,
vm.ctx.none(),
None,
None,
vm,
);
}
struct EscapeWarningVisitor<'a> {
source: &'a str,
filename: &'a str,
vm: &'a VirtualMachine,
}
impl<'a> EscapeWarningVisitor<'a> {
/// Check a quoted string/bytes literal for invalid escapes.
/// The range must include the prefix and quote delimiters.
fn check_quoted_literal(&self, range: TextRange, is_bytes: bool) {
if let Some((start, end)) = content_bounds(self.source, range)
&& let Some((ch, offset)) = first_invalid_escape(self.source, start, end, is_bytes)
{
warn_invalid_escape_sequence(self.source, ch, offset, self.filename, self.vm);
}
}
/// Check an f-string literal element for invalid escapes.
/// The range covers content only (no prefix/quotes).
///
/// Also handles `\{` / `\}` at the literal–interpolation boundary,
/// equivalent to `_PyTokenizer_warn_invalid_escape_sequence` handling
/// `FSTRING_MIDDLE` / `FSTRING_END` tokens.
fn check_fstring_literal(&self, range: TextRange) {
let start = range.start().to_usize();
let end = range.end().to_usize();
if start >= end || end > self.source.len() {
return;
}
if let Some((ch, offset)) = first_invalid_escape(self.source, start, end, false) {
warn_invalid_escape_sequence(self.source, ch, offset, self.filename, self.vm);
return;
}
// In CPython, _PyTokenizer_warn_invalid_escape_sequence handles
// `\{` and `\}` for FSTRING_MIDDLE/FSTRING_END tokens. Ruff
// splits the literal element before the interpolation delimiter,
// so the `\` sits at the end of the literal range and the `{`/`}`
// sits just after it. Only warn when the number of trailing
// backslashes is odd (an even count means they are all escaped).
let trailing_bs = self.source.as_bytes()[start..end]
.iter()
.rev()
.take_while(|&&b| b == b'\\')
.count();
if trailing_bs % 2 == 1
&& let Some(&after) = self.source.as_bytes().get(end)
&& (after == b'{' || after == b'}')
{
warn_invalid_escape_sequence(
self.source,
after as char,
end - 1,
self.filename,
self.vm,
);
}
}
/// Visit f-string elements, checking literals and recursing into
/// interpolation expressions and format specs.
fn visit_fstring_elements(&mut self, elements: &'a ast::InterpolatedStringElements) {
for element in elements {
match element {
ast::InterpolatedStringElement::Literal(lit) => {
self.check_fstring_literal(lit.range);
}
ast::InterpolatedStringElement::Interpolation(interp) => {
self.visit_expr(&interp.expression);
if let Some(spec) = &interp.format_spec {
self.visit_fstring_elements(&spec.elements);
}
}
}
}
}
}
impl<'a> Visitor<'a> for EscapeWarningVisitor<'a> {
fn visit_expr(&mut self, expr: &'a ast::Expr) {
match expr {
// Regular string literals — decode_unicode_with_escapes path
ast::Expr::StringLiteral(string) => {
for part in string.value.as_slice() {
if !matches!(
part.flags.prefix(),
ast::str_prefix::StringLiteralPrefix::Raw { .. }
) {
self.check_quoted_literal(part.range, false);
}
}
}
// Byte string literals — decode_bytes_with_escapes path
ast::Expr::BytesLiteral(bytes) => {
for part in bytes.value.as_slice() {
if !matches!(
part.flags.prefix(),
ast::str_prefix::ByteStringPrefix::Raw { .. }
) {
self.check_quoted_literal(part.range, true);
}
}
}
// F-string literals — tokenizer + string_parser paths
ast::Expr::FString(fstring_expr) => {
for part in fstring_expr.value.as_slice() {
match part {
ast::FStringPart::Literal(string_lit) => {
// Plain string part in f-string concatenation
if !matches!(
string_lit.flags.prefix(),
ast::str_prefix::StringLiteralPrefix::Raw { .. }
) {
self.check_quoted_literal(string_lit.range, false);
}
}
ast::FStringPart::FString(fstring) => {
if matches!(
fstring.flags.prefix(),
ast::str_prefix::FStringPrefix::Raw { .. }
) {
continue;
}
self.visit_fstring_elements(&fstring.elements);
}
}
}
}
_ => ast::visitor::walk_expr(self, expr),
}
}
}
impl VirtualMachine {
/// Walk all string literals in `source` and emit `SyntaxWarning` for
/// each that contains an invalid escape sequence.
pub(super) fn emit_string_escape_warnings(&self, source: &str, filename: &str) {
let Ok(parsed) =
ruff_python_parser::parse(source, ruff_python_parser::Mode::Module.into())
else {
return;
};
let ast = parsed.into_syntax();
let mut visitor = EscapeWarningVisitor {
source,
filename,
vm: self,
};
match ast {
ast::Mod::Module(module) => {
for stmt in &module.body {
visitor.visit_stmt(stmt);
}
}
ast::Mod::Expression(expr) => {
visitor.visit_expr(&expr.body);
}
}
}
}
}