Skip to content

Commit

Permalink
Better handling of SyntaxErrors (#201)
Browse files Browse the repository at this point in the history
Sometimes need to find the ERROR node to properly print the line number.

Also adjusted the printing of the error to go to stderr with full file
name.

Signed-off-by: Eric Brown <eric.brown@securesauce.dev>
  • Loading branch information
ericwb authored Jan 10, 2024
1 parent 9a2b547 commit 282fc55
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
6 changes: 5 additions & 1 deletion precli/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,11 @@ def parse_file(
except KeyboardInterrupt:
sys.exit(2)
except SyntaxError as e:
print(e)
print(
f"Syntax error while parsing file. ({e.filename}, "
f"line {e.lineno})",
file=sys.stderr,
)
files_skipped.append((fname, e))
new_file_list.remove(fname)
except Exception as e:
Expand Down
14 changes: 9 additions & 5 deletions precli/parsers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,19 @@ def visit_comment(self, nodes: list[Node]):
# TODO: add the justification to the suppression

def visit_ERROR(self, nodes: list[Node]):
err_node = self.first_match(self.context["node"], "ERROR")
if err_node is None:
err_node = self.context["node"]

raise SyntaxError(
"Syntax error while parsing file.",
(
self.context["file_name"],
self.context["node"].start_point[0] + 1,
self.context["node"].start_point[1] + 1,
self.context["node"].text.decode(),
self.context["node"].end_point[0] + 1,
self.context["node"].end_point[1] + 1,
err_node.start_point[0] + 1,
err_node.start_point[1] + 1,
err_node.text.decode(errors="ignore"),
err_node.end_point[0] + 1,
err_node.end_point[1] + 1,
),
)

Expand Down

0 comments on commit 282fc55

Please sign in to comment.