Skip to content

Commit a8ea671

Browse files
authored
adjusted SyntaxError args and __str__() to match CPython (RustPython#5294)
1 parent 64a464a commit a8ea671

6 files changed

Lines changed: 170 additions & 72 deletions

File tree

‎Lib/test/test_fstring.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1196,8 +1196,6 @@ def test_errors(self):
11961196
r"f'{1000:j}'",
11971197
])
11981198

1199-
# TODO: RUSTPYTHON
1200-
@unittest.expectedFailure
12011199
def test_filename_in_syntaxerror(self):
12021200
# see issue 38964
12031201
with temp_cwd() as cwd:

‎Lib/test/test_future_stmt/test_future.py‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,57 +52,41 @@ def test_future_multiple_features(self):
5252
):
5353
from test.test_future_stmt import test_future_multiple_features
5454

55-
# TODO: RUSTPYTHON
56-
@unittest.expectedFailure
5755
def test_badfuture3(self):
5856
with self.assertRaises(SyntaxError) as cm:
5957
from test.test_future_stmt import badsyntax_future3
6058
self.check_syntax_error(cm.exception, "badsyntax_future3", 3)
6159

62-
# TODO: RUSTPYTHON
63-
@unittest.expectedFailure
6460
def test_badfuture4(self):
6561
with self.assertRaises(SyntaxError) as cm:
6662
from test.test_future_stmt import badsyntax_future4
6763
self.check_syntax_error(cm.exception, "badsyntax_future4", 3)
6864

69-
# TODO: RUSTPYTHON
70-
@unittest.expectedFailure
7165
def test_badfuture5(self):
7266
with self.assertRaises(SyntaxError) as cm:
7367
from test.test_future_stmt import badsyntax_future5
7468
self.check_syntax_error(cm.exception, "badsyntax_future5", 4)
7569

76-
# TODO: RUSTPYTHON
77-
@unittest.expectedFailure
7870
def test_badfuture6(self):
7971
with self.assertRaises(SyntaxError) as cm:
8072
from test.test_future_stmt import badsyntax_future6
8173
self.check_syntax_error(cm.exception, "badsyntax_future6", 3)
8274

83-
# TODO: RUSTPYTHON
84-
@unittest.expectedFailure
8575
def test_badfuture7(self):
8676
with self.assertRaises(SyntaxError) as cm:
8777
from test.test_future_stmt import badsyntax_future7
8878
self.check_syntax_error(cm.exception, "badsyntax_future7", 3, 54)
8979

90-
# TODO: RUSTPYTHON
91-
@unittest.expectedFailure
9280
def test_badfuture8(self):
9381
with self.assertRaises(SyntaxError) as cm:
9482
from test.test_future_stmt import badsyntax_future8
9583
self.check_syntax_error(cm.exception, "badsyntax_future8", 3)
9684

97-
# TODO: RUSTPYTHON
98-
@unittest.expectedFailure
9985
def test_badfuture9(self):
10086
with self.assertRaises(SyntaxError) as cm:
10187
from test.test_future_stmt import badsyntax_future9
10288
self.check_syntax_error(cm.exception, "badsyntax_future9", 3)
10389

104-
# TODO: RUSTPYTHON
105-
@unittest.expectedFailure
10690
def test_badfuture10(self):
10791
with self.assertRaises(SyntaxError) as cm:
10892
from test.test_future_stmt import badsyntax_future10

‎vm/src/exceptions.rs‎

Lines changed: 169 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,11 @@ impl VirtualMachine {
142142
let args_repr = vm.exception_args_as_string(varargs, true);
143143

144144
let exc_class = exc.class();
145+
146+
if exc_class.fast_issubclass(vm.ctx.exceptions.syntax_error) {
147+
return self.write_syntaxerror(output, exc, exc_class, &args_repr);
148+
}
149+
145150
let exc_name = exc_class.name();
146151
match args_repr.len() {
147152
0 => write!(output, "{exc_name}"),
@@ -150,7 +155,119 @@ impl VirtualMachine {
150155
output,
151156
"{}: ({})",
152157
exc_name,
153-
args_repr.into_iter().format(", ")
158+
args_repr.into_iter().format(", "),
159+
),
160+
}?;
161+
162+
match offer_suggestions(exc, vm) {
163+
Some(suggestions) => writeln!(output, ". Did you mean: '{suggestions}'?"),
164+
None => writeln!(output),
165+
}
166+
}
167+
168+
/// Format and write a SyntaxError
169+
/// This logic is derived from TracebackException._format_syntax_error
170+
///
171+
/// The logic has support for `end_offset` to highlight a range in the source code,
172+
/// but it looks like `end_offset` is not used yet when SyntaxErrors are created.
173+
fn write_syntaxerror<W: Write>(
174+
&self,
175+
output: &mut W,
176+
exc: &PyBaseExceptionRef,
177+
exc_type: &Py<PyType>,
178+
args_repr: &[PyRef<PyStr>],
179+
) -> Result<(), W::Error> {
180+
let vm = self;
181+
debug_assert!(exc_type.fast_issubclass(vm.ctx.exceptions.syntax_error));
182+
183+
let getattr = |attr: &'static str| exc.as_object().get_attr(attr, vm).ok();
184+
185+
let maybe_lineno = getattr("lineno").map(|obj| {
186+
obj.str(vm)
187+
.unwrap_or_else(|_| vm.ctx.new_str("<lineno str() failed>"))
188+
});
189+
let maybe_filename = getattr("filename").and_then(|obj| obj.str(vm).ok());
190+
191+
let maybe_text = getattr("text").map(|obj| {
192+
obj.str(vm)
193+
.unwrap_or_else(|_| vm.ctx.new_str("<text str() failed>"))
194+
});
195+
196+
let mut filename_suffix = String::new();
197+
198+
if let Some(lineno) = maybe_lineno {
199+
writeln!(
200+
output,
201+
r##" File "{}", line {}"##,
202+
maybe_filename
203+
.as_ref()
204+
.map(|s| s.as_str())
205+
.unwrap_or("<string>"),
206+
lineno
207+
)?;
208+
} else if let Some(filename) = maybe_filename {
209+
filename_suffix = format!(" ({})", filename);
210+
}
211+
212+
if let Some(text) = maybe_text {
213+
// if text ends with \n, remove it
214+
let rtext = text.as_str().trim_end_matches('\n');
215+
let ltext = rtext.trim_start_matches([' ', '\n', '\x0c']); // \x0c is \f
216+
let spaces = (rtext.len() - ltext.len()) as isize;
217+
218+
writeln!(output, " {}", ltext)?;
219+
220+
let maybe_offset: Option<isize> =
221+
getattr("offset").and_then(|obj| obj.try_to_value::<isize>(vm).ok());
222+
223+
if let Some(offset) = maybe_offset {
224+
let maybe_end_offset: Option<isize> =
225+
getattr("end_offset").and_then(|obj| obj.try_to_value::<isize>(vm).ok());
226+
227+
let mut end_offset = match maybe_end_offset {
228+
Some(0) | None => offset,
229+
Some(end_offset) => end_offset,
230+
};
231+
232+
if offset == end_offset || end_offset == -1 {
233+
end_offset = offset + 1;
234+
}
235+
236+
// Convert 1-based column offset to 0-based index into stripped text
237+
let colno = offset - 1 - spaces;
238+
let end_colno = end_offset - 1 - spaces;
239+
if colno >= 0 {
240+
let caretspace = ltext.chars().collect::<Vec<_>>()[..colno as usize]
241+
.iter()
242+
.map(|c| if c.is_whitespace() { *c } else { ' ' })
243+
.collect::<String>();
244+
245+
let mut error_width = end_colno - colno;
246+
if error_width < 1 {
247+
error_width = 1;
248+
}
249+
250+
writeln!(
251+
output,
252+
" {}{}",
253+
caretspace,
254+
"^".repeat(error_width as usize)
255+
)?;
256+
}
257+
}
258+
}
259+
260+
let exc_name = exc_type.name();
261+
262+
match args_repr.len() {
263+
0 => write!(output, "{exc_name}{filename_suffix}"),
264+
1 => write!(output, "{}: {}{}", exc_name, args_repr[0], filename_suffix),
265+
_ => write!(
266+
output,
267+
"{}: ({}){}",
268+
exc_name,
269+
args_repr.iter().format(", "),
270+
filename_suffix
154271
),
155272
}?;
156273

@@ -1461,10 +1578,60 @@ pub(super) mod types {
14611578
#[derive(Debug)]
14621579
pub struct PyRecursionError {}
14631580

1464-
#[pyexception(name, base = "PyException", ctx = "syntax_error", impl)]
1581+
#[pyexception(name, base = "PyException", ctx = "syntax_error")]
14651582
#[derive(Debug)]
14661583
pub struct PySyntaxError {}
14671584

1585+
#[pyexception]
1586+
impl PySyntaxError {
1587+
#[pymethod(magic)]
1588+
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
1589+
fn basename(filename: &str) -> &str {
1590+
let splitted = if cfg!(windows) {
1591+
filename.rsplit(&['/', '\\']).next()
1592+
} else {
1593+
filename.rsplit('/').next()
1594+
};
1595+
splitted.unwrap_or(filename)
1596+
}
1597+
1598+
let maybe_lineno = exc.as_object().get_attr("lineno", vm).ok().map(|obj| {
1599+
obj.str(vm)
1600+
.unwrap_or_else(|_| vm.ctx.new_str("<lineno str() failed>"))
1601+
});
1602+
let maybe_filename = exc.as_object().get_attr("filename", vm).ok().map(|obj| {
1603+
obj.str(vm)
1604+
.unwrap_or_else(|_| vm.ctx.new_str("<filename str() failed>"))
1605+
});
1606+
1607+
let args = exc.args();
1608+
1609+
let msg = if args.len() == 1 {
1610+
vm.exception_args_as_string(args, false)
1611+
.into_iter()
1612+
.exactly_one()
1613+
.unwrap()
1614+
} else {
1615+
return exc.str(vm);
1616+
};
1617+
1618+
let msg_with_location_info: String = match (maybe_lineno, maybe_filename) {
1619+
(Some(lineno), Some(filename)) => {
1620+
format!("{} ({}, line {})", msg, basename(filename.as_str()), lineno)
1621+
}
1622+
(Some(lineno), None) => {
1623+
format!("{} (line {})", msg, lineno)
1624+
}
1625+
(None, Some(filename)) => {
1626+
format!("{} ({})", msg, basename(filename.as_str()))
1627+
}
1628+
(None, None) => msg.to_string(),
1629+
};
1630+
1631+
vm.ctx.new_str(msg_with_location_info)
1632+
}
1633+
}
1634+
14681635
#[pyexception(name, base = "PySyntaxError", ctx = "indentation_error", impl)]
14691636
#[derive(Debug)]
14701637
pub struct PyIndentationError {}

‎vm/src/lib.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ pub mod scope;
7373
pub mod sequence;
7474
pub mod signal;
7575
pub mod sliceable;
76-
mod source;
7776
pub mod stdlib;
7877
pub mod suggestion;
7978
pub mod types;

‎vm/src/source.rs‎

Lines changed: 0 additions & 20 deletions
This file was deleted.

‎vm/src/vm/vm_new.rs‎

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,6 @@ impl VirtualMachine {
262262
error: &crate::compiler::CompileError,
263263
source: Option<&str>,
264264
) -> PyBaseExceptionRef {
265-
use crate::source::AtLocation;
266265
use crate::source_code::SourceLocation;
267266

268267
let syntax_error_type = match &error.error {
@@ -293,36 +292,7 @@ impl VirtualMachine {
293292
None
294293
};
295294

296-
fn fmt(
297-
error: &crate::compiler::CompileError,
298-
statement: Option<&str>,
299-
f: &mut impl std::fmt::Write,
300-
) -> std::fmt::Result {
301-
let loc = error.location;
302-
if let Some(ref stmt) = statement {
303-
// visualize the error when location and statement are provided
304-
write!(
305-
f,
306-
"{error}{at_location}\n{stmt}{arrow:>pad$}",
307-
error = error.error,
308-
at_location = AtLocation(loc.as_ref()),
309-
pad = loc.map_or(0, |loc| loc.column.to_usize()),
310-
arrow = "^"
311-
)
312-
} else {
313-
write!(
314-
f,
315-
"{error}{at_location}",
316-
error = error.error,
317-
at_location = AtLocation(loc.as_ref()),
318-
)
319-
}
320-
}
321-
322-
let mut msg = String::new();
323-
fmt(error, statement.as_deref(), &mut msg).unwrap();
324-
325-
let syntax_error = self.new_exception_msg(syntax_error_type, msg);
295+
let syntax_error = self.new_exception_msg(syntax_error_type, error.error.to_string());
326296
let (lineno, offset) = error.python_location();
327297
let lineno = self.ctx.new_int(lineno);
328298
let offset = self.ctx.new_int(offset);

0 commit comments

Comments
 (0)