Skip to content

Commit a0cd64e

Browse files
authored
[Fix] use py_compile for pyi file syntax check (PaddlePaddle#71872)
1 parent 11a95ee commit a0cd64e

File tree

1 file changed

+23
-28
lines changed

1 file changed

+23
-28
lines changed

tools/gen_pybind11_stub.py

Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
from __future__ import annotations
1616

1717
import argparse
18-
import ast
1918
import functools
2019
import keyword
2120
import logging
2221
import os
22+
import py_compile
2323
import re
2424
import shutil
2525
import tempfile
@@ -323,59 +323,54 @@ def wrap_text(text):
323323
f.write(stub_file)
324324

325325

326-
def check_remove_syntax_error(filename, limit=1000):
326+
def check_remove_syntax_error(filename: str, limit: int = 10000):
327327
"""
328328
Args:
329329
filename: xxx.pyi
330-
limit: check limit, or raise error
330+
limit: the max times try to check syntax error
331331
"""
332332
pattern_check = re.compile(
333333
rf"File.*{re.escape(filename)}.*line (?P<lineno>\d+)"
334334
)
335335

336-
while limit:
336+
while limit > 0:
337+
337338
limit -= 1
338339

339-
# read file and check syntax error
340+
# check syntax error
340341
err = ""
341-
source = ""
342-
source_lines = []
343-
with open(filename, "r", encoding="utf-8") as f:
344-
source_lines = f.readlines()
345-
source = "".join(source_lines)
346-
347-
is_valid = True
348-
349-
try:
350-
ast.parse(source, filename)
351-
except SyntaxError:
352-
is_valid = False
353-
err = traceback.format_exc()
354342

355-
if is_valid:
356-
break
357-
else:
358-
if limit <= 0:
359-
print(f">>> Syntax error detected in file: {filename}")
343+
try:
344+
py_compile.compile(filename, doraise=True)
345+
break
346+
except py_compile.PyCompileError as e:
347+
err = traceback.format_exc()
360348

361349
print(f">>> Syntax error: find syntax error in file: {filename}")
362350

363351
# find the line with syntax error
364352
match_obj = pattern_check.search(err)
365353
if match_obj is not None:
366354
line_no = int(match_obj.group("lineno"))
355+
356+
# read file
357+
source_lines = []
358+
with open(filename, "r", encoding="utf-8") as f:
359+
source_lines = f.readlines()
360+
361+
del source_lines[line_no - 1]
362+
363+
# write new lines
364+
with open(filename, "w", encoding="utf-8") as f:
365+
f.writelines(source_lines)
366+
367367
print(
368368
f">>> Syntax error: remove the error line {line_no}, and continue to check ..."
369369
)
370-
del source_lines[line_no - 1]
371370
else:
372371
print(">>> Syntax error: no match obj, just continue ...")
373372
break
374373

375-
# write new lines
376-
with open(filename, "w", encoding="utf-8") as f:
377-
f.writelines(source_lines)
378-
379374

380375
def post_process(output_dir: str):
381376
"""

0 commit comments

Comments
 (0)