@@ -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 { }
0 commit comments