1
1
import json
2
+ import subprocess
2
3
3
4
def 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
+ """
4
20
try :
5
21
stripped_lines = []
6
22
with open (file_path , "r" ) as f :
@@ -14,7 +30,21 @@ def print_code_snippet(file_path, line_num, context=3):
14
30
except Exception as e :
15
31
print (f"Could not read file { file_path } : { e } " )
16
32
33
+
17
34
def 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
+ """
18
48
for line in stderr .splitlines ():
19
49
line = line .strip ()
20
50
if not line :
@@ -46,14 +76,30 @@ def parse_rustc_json(stderr: str, file):
46
76
else :
47
77
print (f"{ level } : { msg } " )
48
78
49
- import subprocess
79
+
50
80
def 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
+ """
51
94
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.
52
97
result = subprocess .run (
53
- ["rustc" , "--test" , "--edition=2021 " , "--error-format=json" , rs_path ],
98
+ ["rustc" , "--test" , "--edition=2024 " , "--error-format=json" , rs_path ],
54
99
capture_output = True ,
55
100
text = True
56
101
)
102
+
57
103
if result .returncode != 0 :
58
104
print ("--- rustc Errors/Warnings ---" )
59
105
parse_rustc_json (result .stderr , app .output_rust_file )
0 commit comments