11import json
2+ import subprocess
23
34def print_code_snippet (file_path , line_num , context = 3 ):
5+ """
6+ Prints a code snippet from a file with context around a specific line.
7+
8+ This function is typically used to display source code around an error line
9+ for better debugging and error reporting.
10+
11+ Args:
12+ file_path (str): Path to the source file.
13+ line_num (int): The line number where the error occurred (1-based index).
14+ context (int, optional): The number of lines to display before and after
15+ the error line. Defaults to 3.
16+
17+ Returns:
18+ None
19+ """
420 try :
521 stripped_lines = []
622 with open (file_path , "r" ) as f :
@@ -14,7 +30,21 @@ def print_code_snippet(file_path, line_num, context=3):
1430 except Exception as e :
1531 print (f"Could not read file { file_path } : { e } " )
1632
33+
1734def parse_rustc_json (stderr : str , file ):
35+ """
36+ Parses the JSON diagnostics output from `rustc`.
37+
38+ This function takes the standard error output (in JSON format) from the Rust compiler (`rustc`)
39+ and processes it, possibly filtering or reporting diagnostics relevant to the specified file.
40+
41+ Args:
42+ stderr (str): The JSON-formatted stderr output from `rustc`.
43+ file: The file object or path that the diagnostics should relate to.
44+
45+ Returns:
46+ Any
47+ """
1848 for line in stderr .splitlines ():
1949 line = line .strip ()
2050 if not line :
@@ -46,14 +76,30 @@ def parse_rustc_json(stderr: str, file):
4676 else :
4777 print (f"{ level } : { msg } " )
4878
49- import subprocess
79+
5080def check_rust_test_errors (app , exception ):
81+ """
82+ Sphinx 'build-finished' event handler that compiles the generated Rust file in test mode.
83+
84+ This function is connected to the Sphinx build lifecycle and is executed after the build finishes.
85+ It invokes `rustc` in test mode on the generated Rust file and reports any compilation or test-related
86+ errors.
87+
88+ Args:
89+ app: The Sphinx application object. Must have an `output_rust_file` attribute containing
90+ the path to the generated Rust source file.
91+ exception: Exception raised during the build process, or None if the build completed successfully.
92+
93+ """
5194 rs_path = app .output_rust_file
95+ # Run the Rust compiler in test mode with JSON error output format.
96+ # capturing stdout and stderr as text.
5297 result = subprocess .run (
53- ["rustc" , "--test" , "--edition=2021 " , "--error-format=json" , rs_path ],
98+ ["rustc" , "--test" , "--edition=2024 " , "--error-format=json" , rs_path ],
5499 capture_output = True ,
55100 text = True
56101 )
102+
57103 if result .returncode != 0 :
58104 print ("--- rustc Errors/Warnings ---" )
59105 parse_rustc_json (result .stderr , app .output_rust_file )
0 commit comments